Categories
android blog koin kotlin

Koin and arguments injection

In previous articles, we explored the basics of Koin. In this article let’s look at more advanced uses of Koin, in particular how to provide constructor dependencies.

Let’s say that we have a details view which needs a presenter, that presenter, in turn, needs an item id which can be used to request item details from the backend. In Koin, we can just provide a lambda with an argument instead of our dependency directly, for example:

class Presenter(val id : Long)
    val myModule = module {
         single { (id : Long) -> Presenter(id) }
    }

Now in our view (activity/fragment), we can just inject the presenter like this

val id = getIdFromArguments()
val presenter : Presenter by inject { parametersOf(id) }

What if we want to resolve a dependency directly in a Koin module for a particular class? We can use get() to eagerly load our dependency, for example:

val dataModule = module {
    single { UserSession() }
    single { UserRepository(get()) }
}
class UserRepository(private val userSession: UserSession)

In the example above UserRepository class depends on UserSession class and we can provide UserSession instance by simply writing get() which will walk our dependency graph in Koin and grab an instance of UserSession().

Now, can you spot a problem with the way we provide constructor arguments for UserRepository class? What will happen when we change the constructor for UserRepository class? The code above won’t compile! Why? Because we need to write another get() for the second argument, for example:

val dataModule = module {
    single { LocalStorage() }
    single { UserSession() }
    single { UserRepository(get(), get()) }
}
class UserRepository(private val userSession: UserSession,
                     private val localStorage: LocalStorage)

And this is the downside of Koin and the runtime dependency injection, Dagger can automatically write wiring for the new constructor during compile time, and we don’t have to modify anything. Fortunately this is a compile-time error and we will be warned by the Android studio promptly.

Stay tuned for the next article!

Leave a Reply

Your email address will not be published. Required fields are marked *