8

Dependency Injection with Kodein & MVVM Architecture – Android Kotlin Tutorial

Not a single software developer ever said that a more loosely coupled code gives him headaches. On the contrary, tight coupling can and will create a bunch of things that are hard to deal with.

But first, what is that “loose coupling”? Loose coupling means not instantiating dependencies of a class directly but getting them from a centralized place. Dependencies are simply classes which are needed by other classes. For example, a view model needs a repository, so the repository is a dependency of the view model.

Loose coupling also means that your classes operate with their dependencies through an interface and not directly with their concrete implementation. This allows you to swap implementations really easily. For example, a production implementation of a database will store data on a remote server, while a test implementation will store data only locally.

In this tutorial you are going to learn how to put what’s written above into practice by using a dependency injection framework called Kodein. It is specifically designed to work well with Kotlin and it’s also compatible with Java.

?Get the code from this tutorial?

 

Matej Rešetár
 

Matej is an app developer with a knack for teaching others. If he's not programming, making tutorials or doing other business, he's mostly working out, listening to audiobooks and taking cold showers.

  • Rainzo says:

    I have learned a lot from your tutorials and have slowly gotten more comfortable with MVVM and Kotlin on Android (coming from Xamarin world and finally favoring native dev instead).

    Please can you make this sample include validation because that’s something I’m struggling with.
    By validation I mean, the button should be disabled unless both input texts are filled up. Thanks. Or at least can you make a little tutorial like that as I am not sure how to handle validation with 2 or more edit texts

  • yazan says:

    I craete same app exactly with same code but i got this error in QuoteActivity on line code
    val viewModel= ViewModelProviders.of(this,factory).get(QuotesViewModel::class.java)

    the error : Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to org.kodein.di.KodeinAware

  • Mahdi Pishguy says:

    Great tutorial. thansk

    could you help us how can i save data into database with this implementation? you create some class as DataBase in this project structure and i’m not sure how can save data in database,

    you save data from viewModel or repository class or Activity?

    Thanks in advance

  • >