Getting started with Android & Architecture Components

Let’s start with Koin on a simple Android app & ModelView classes

Gradle Setup

Add the Koin Android Architecture dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()
}
dependencies {
    // Koin for Android Architecture Components
    compile 'org.koin:koin-android-architecture:0.9.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 ViewModel class, for consuming this data:

// Use Repository - injected by constructor by Koin
class MyViewModel(val repository : Repository) : ViewModel(){

    fun sayHello() = repository.giveHello()

    override fun onCleared() {} 
}

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

// Koin module
val myModule : Module = applicationContext {
    viewModel { MyViewModel(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 MyViewModel component will be created with Repository instance. To get it into our Activity, let’s inject it with the by viewModel() function:

class MyActivity : AppCompatActivity(){

    // Lazy property
    val model by viewModel<MyViewModel>()

    override fun onCreate() {
        super.onCreate()

        Log.i("MyActivity","viewmodel : ${model.sayHello()}")
    }
}
class MyActivity : AppCompatActivity(){

    override fun onCreate() {
        super.onCreate()

        // Create the ViewModel
        val model  = getViewModel<MyViewModel>()
        
        Log.i("MyActivity","viewmodel : ${model.sayHello()}")
    }
}

What’s Next?

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

General Topics

Developer Guide

Soon…