Dependency Inversion in Android

When it comes to Android app development, there are a few dependency inversion options that have become popular.

Java: Dagger 2

The de facto dependency injection standard for Java app development is Dagger. It is very powerful, but that power comes with a lot of confusion and complexity.

Dagger uses annotations to indicate how the dependencies get connected. In our example, annotations would indicate that PassphraseRepository needs a SecureRandom and how that SecureRandom gets created, both for regular code and for tests. Dagger then generates the “glue code” needed to connect those dependencies.

Kotlin: Koin and Kodein

You can use Dagger for Kotlin code as well, though the confusion and complexity increases. For Kotlin-centric projects, there are other options that are simpler to use, though they focus more on runtime dependency inversion rather than compile-time code generation.

The two most popular options for Kotlin appear to be Kodein’s dependency injector and Koin. In this chapter, we will explore the use of Koin.

Koin can be used in Java projects, but it is definitely geared around use in Kotlin. As such, we will only look at Koin in a Kotlin project. The concepts of dependency inversion still hold true for Java, but the implementation in something like Dagger would look quite a bit different.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.