Getting started with Android & Scope feature

Let’s start with Koin on a Android app with scoping feature

About

This tutorial lets you write an Android/Kotlin application and use Koin inject and retrieve your components with scope.

Get the code

Checkout the project directly on Github or download the zip file

Gradle Setup

Add the Koin Android dependency like below:

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

Our components

Let’s create a HelloRepository to provide some data:

interface HelloRepository {
    fun giveHello(): String
}

class HelloRepositoryImpl() : HelloRepository {
    override fun giveHello() = "Hello Koin"
}

Let’s create a presenter class, for consuming this data:

class MyScopePresenter(val repo: HelloRepository) {

    fun sayHello() = "${repo.giveHello()} from $this"
}

Writing the Koin module

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

val appModule = module {

    // single instance of HelloRepository
    single<HelloRepository> { HelloRepositoryImpl() }

    // Scoped MyScopePresenter instance
    scope("session") { MyScopePresenter(get())}
}

Note: we declare our MyScopePresenter class as a scope definition. This will allows us to bind a MyScopePresenter with a scope, and drop this instance with the scope closing.

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(appModule))
    }
}

Injecting dependencies

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

class MyScopeActivity : AppCompatActivity() {

    // inject MyScopePresenter from "session" scope 
    val scopePresenter: MyScopePresenter by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_simple)
        
        // bind "session" scope to component lifecycle
        bindScope(getOrCreateScope("session"))

        //...
    }
}

What’s Next?

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

Also other Android getting started project: