Koin for Dependency Injection in Kotlin MVVM

Tolga Erbaş
2 min readMar 18, 2022

--

What is Dependency Injection?

If you are a newbie to Android application development, probably the one of most important technique is Dependency Injection.

Dependency Injection (DI) is a unique way for classes to refer other classes.

Koin

Implementing DI provides you some advantages

  • Reusability of code
  • Ease of refactoring
  • Ease of testing

For more information, you can visit here. I assume you already know it (if you newbie, you should (: )

In Android ecosystem, there are several ways to implement Dependency Injection. Some of them;

  • Dagger2
  • Kodein
  • Hilt
  • Koin

Android ecosystem is evolving and changing rapidly, so we are looking for easy to use and light-weighted libraries and tools to develop an application.

In this article, I will show you how to easily implement Koin in your projects.

First of all, you need to add these dependencies to build.gradle file, version is 3.1.3 for now. You can check from here

// For Main Features

implementation “io.insert-koin:koin-android:$koin_version”

// For Java Compatibility

implementation “io.insert-koin:koin-android-compat:$koin_version”

Above code implements Retrofit and OkHttp clients. After that we add our API service to this, which is;

And the BinanceModel is a data class for API response.

Then, we will this service in our repository.

So we implement our Retrofit, our API service and repository. Now we will make a request for this. Using repositories, services in ViewModel parameters, you need to add these parameters to Koin. Look at the code below

currencyApiRepository is used in the ViewModel, so we need to add to the Koin.

this is the code that we need to use, any kind of class that we used in the viewmodels, we need to add one more get() to it.

And lastly, we need to initialize the Koin from our App module, we use startKoin to do that.

That’s all. Koin is very easy to use and efficient. If you use Dagger before, you know what I’m saying :)

Thanks for reading, if you like my article about Koin and Dependency Injection in Kotlin, you can like or share to support me.

You can find me in LinkedIn

Check out my other article:

--

--