Getting started with Android

Let’s start with Koin on a simple Android app

Gradle Setup

Add the Koin Android dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    // Koin for Android
    compile 'org.koin:koin-android:0.8.2'
}

Declaring our first dependencies

Let’s create a Repository to provide some data (giveHello()):

interface Repository {
    fun giveHello()
}

class MyRepository() : Repository {
    override fun giveHello() = "Hello Koin"
}

A Presenter class, for consuming this data:

// Use Repository - injected by constructor by Koin
class MyPresenter(val repository : Repository){
    fun sayHello() = repository.giveHello()
}

Use the applicationContext function to declare a module. Let’s declare our first component:

// Koin module
val myModule : Module = applicationContext {
    provide { MyPresenter(get()) } // get() will resolve Repository instance
    provide { MyRepository() as Repository }
}

Start Koin

Now that we have a module, let’s start it with Koin. Open your application class, or make one (don’t forget to declare it in your manifest.xml). Just call the startKoin() function:

class MyApplication : Application(){
    override fun onCreate() {
        super.onCreate()
        // Start Koin
        startKoin(this, listOf(myModule))
    }
}

Injecting dependencies

The MyPresenter component will be created with Repository instance. To get it from our Activity, let’s inject it with the by inject() delegate injector:

class MyActivity : AppCompatActivity(){

    // Inject MyPresenter
    val presenter : MyPresenter by inject()

    override fun onCreate() {
        super.onCreate()
        // Let's use our presenter
        Log.i("MyActivity","presenter : ${presenter.sayHello()}")
    }
}

What’s Next?

You have finished this starting tutorial. Below are some topics for further reading:

General Topics

Advanced Android Topics