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 {
    maven {
      url  "" 
dependencies {
    // Koin for Android Architecture Components
    compile 'org.koin:koin-android-architecture: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 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() {
        // Start Koin
        startKoin(this, listOf(myModule))

Injecting dependencies

The MyViewModel component will be created with Repository instance. To get it from our Activity, let’s inject it with the getViewModel() function:

class MyActivity : AppCompatActivity(){

    override fun onCreate() {
        // Let's get our 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

Advanced Android Topics