Koin as an alternative

Learn how Koin dependency injection works in Android, compare it to Hilt, and use Kotlin DSL to catch runtime graph errors before deployment. About 20 minutes.

Why it matters

  • Interviews often ask you to compare compile-time DI (Hilt) with runtime DI (Koin), and to do it fairly.
  • Koin is a common choice for Kotlin Multiplatform (KMP) projects, because Hilt is Android-only.
  • Koin's graph is checked only when it runs, so a missing definition can ship unless you add a check; knowing the check is part of using Koin well.
  • Plenty of production apps use Koin, so you may join a codebase that does.

The simple explanation

  • A restaurant with a fixed menu (Hilt): the kitchen checks every recipe against the pantry before opening. A missing ingredient stops the restaurant from opening (a build error).
  • A restaurant that cooks to order (Koin): the waiter checks the pantry when you order. A missing ingredient is found at your table (a runtime error), unless someone walked through every recipe before service (a verify() test).

Hilt generates its graph with an annotation processor at build time. Koin builds its graph at runtime: you describe definitions in a Kotlin DSL, startKoin loads them into a container, and each get() resolves a type when it is called. There is no code generation in the classic DSL.

Koin is usually described as a DI framework; internally its container is a registry looked up at runtime, much like a service locator. Your classes still use constructor injection as long as only the module definitions call get(). Calling get() or inject() inside ordinary classes turns it into service-locator code.

HiltKoin (classic DSL)
Graph builtAt build time, by KSP (or kapt)At runtime, from a Kotlin DSL
Missing definitionBuild errorNoDefinitionFoundException when first resolved, unless a verify() test or compile-time plugin catches it
Kotlin MultiplatformAndroid onlyShared code for Android, iOS, desktop, server
Android integration@AndroidEntryPoint, @HiltViewModel, @HiltWorkerandroidContext, viewModel, koinViewModel(), KoinWorkerFactory

Definitions (Koin 4):

  • single { Api(get()) } or singleOf(::Api): one instance per Koin container, created on first use.
  • factory { Mapper() } or factoryOf(::Mapper): a new instance every time it is resolved.
  • viewModel { DetailViewModel(get()) } or viewModelOf(::DetailViewModel): a ViewModel that is stored in the caller's ViewModelStoreOwner, so it survives rotation like any ViewModel.
  • scope<MyActivity> { scoped { ... } }: an instance tied to a custom scope, such as an Activity's lifetime.
  • bind<Interface>() (or single<Interface> { Impl() }) exposes an implementation as its interface.

Setup. In Application.onCreate() call startKoin { androidLogger(); androidContext(this@App); modules(appModule) }. In Compose, koinViewModel() obtains a ViewModel; in an Activity or Fragment, by viewModel() and by inject().

Checking the graph. appModule.verify() from koin-test (marked experimental) checks in a JVM unit test that every constructor parameter of every definition has a definition. checkModules() is deprecated since Koin 4.0. Koin Annotations (KSP) and the newer Koin compiler plugin can check the graph at build time if you need that.

Notes

  • Koin resolves dependencies at runtime. A missing definition throws NoDefinitionFoundException the first time that type is resolved, which may be deep inside a screen users rarely open.
  • single is one instance per Koin container (per process in a normal app). Use it for expensive or shared objects: an HTTP client, a database, a repository with a cache.
  • factory gives a new instance on every resolution. Use it for cheap, stateless objects.
  • viewModel / viewModelOf declare ViewModels; koinViewModel() (Compose) and by viewModel() (Activity, Fragment) obtain them from the right ViewModelStoreOwner. A SavedStateHandle constructor parameter is supplied automatically.
  • Values only the caller knows are passed with parametersOf(...) and read in the definition, for example viewModel { (id: String) -> DetailViewModel(id, get()) }.
  • Keep get() inside module definitions. A class that calls get() or inject() itself hides its dependencies and is harder to test.
  • Add a verify() test (or Koin Annotations / the compiler plugin) so missing definitions fail CI instead of crashing users. Types Koin supplies at runtime, like Context or SavedStateHandle, are passed to verify(extraTypes = ...).
  • In tests that call startKoin, call stopKoin() afterwards (or use KoinTestRule); otherwise the next test fails with "A Koin Application has already been started".
  • Koin works in KMP shared code, which is the main reason KMP projects pick it. Hilt has no iOS or desktop support.

Code example

A Koin setup for an Android app: a module with single, factory and viewModelOf, startKoin in the Application, a Composable that gets the ViewModel, and a test that verifies the module.

// AppModule.kt
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.module
 
interface Analytics { fun log(event: String) }
class LogcatAnalytics : Analytics {
    override fun log(event: String) { android.util.Log.d("Analytics", event) }
}
 
class DateFormatter { fun format(millis: Long): String = java.time.Instant.ofEpochMilli(millis).toString() }
 
class UserRepository(private val analytics: Analytics) {
    fun login(name: String): String { analytics.log("login"); return name }
}
 
class LoginViewModel(
    private val repository: UserRepository,
    private val formatter: DateFormatter,
    private val savedState: SavedStateHandle, // supplied by Koin
) : ViewModel() {
    fun login(name: String) = repository.login(name)
}
 
val appModule = module {
    singleOf(::LogcatAnalytics) { bind<Analytics>() } // one instance, exposed as the interface
    singleOf(::UserRepository)
    factoryOf(::DateFormatter)                          // new instance each time
    viewModelOf(::LoginViewModel)
}
 
// App.kt (registered in the manifest)
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
 
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger()
            androidContext(this@App)
            modules(appModule)
        }
    }
}
 
// LoginScreen.kt
import androidx.compose.runtime.Composable
import org.koin.compose.viewmodel.koinViewModel
 
@Composable
fun LoginScreen(viewModel: LoginViewModel = koinViewModel()) {
    // ...
}
 
// AppModuleTest.kt (src/test, koin-test)
import androidx.lifecycle.SavedStateHandle
import org.koin.core.annotation.KoinExperimentalAPI
import org.koin.test.verify.verify
import kotlin.test.Test
 
class AppModuleTest {
    @OptIn(KoinExperimentalAPI::class)
    @Test
    fun appModuleIsComplete() {
        appModule.verify(extraTypes = listOf(SavedStateHandle::class))
    }
}
  • singleOf(::UserRepository) reads the constructor and resolves Analytics with get() for you; single { UserRepository(get()) } is the same definition written by hand.
  • bind<Analytics>() lets UserRepository ask for the interface. Without it, Analytics would have no definition and verify() would fail.
  • koinViewModel() comes from koin-compose-viewmodel; it stores the ViewModel in the current ViewModelStoreOwner, so rotation returns the same instance.
  • If someone deletes factoryOf(::DateFormatter), the app still compiles and crashes when the login screen opens. The verify() test fails in CI instead.

Run the idea in plain Kotlin

A tiny runtime container in the spirit of Koin: definitions are lambdas stored in a map, single caches, factory does not, and a missing definition only fails when something asks for it.

import kotlin.reflect.KClass

class NoDefinitionFound(type: String) : Exception("No definition found for " + type)

class Container {
  private val factories = mutableMapOf<KClass<*>, () -> Any>()
  private val singles = mutableMapOf<KClass<*>, Any>()

  fun <T : Any> single(type: KClass<T>, create: Container.() -> T) {
      factories[type] = { singles.getOrPut(type) { create() } }
  }

  fun <T : Any> factory(type: KClass<T>, create: Container.() -> T) {
      factories[type] = { create() }
  }

  @Suppress("UNCHECKED_CAST")
  fun <T : Any> get(type: KClass<T>): T =
      (factories[type] ?: throw NoDefinitionFound(type.simpleName ?: "?")).invoke() as T
}

inline fun <reified T : Any> Container.get(): T = get(T::class)

class HttpClient
class Formatter
class Repo(val client: HttpClient, val formatter: Formatter)
class Settings(val repo: Repo)

fun main() {
  val koin = Container()
  // module { single { HttpClient() }; factory { Formatter() }; factory { Repo(get(), get()) } }
  koin.single(HttpClient::class) { HttpClient() }
  koin.factory(Formatter::class) { Formatter() }
  koin.factory(Repo::class) { Repo(get(), get()) }

  val a = koin.get<Repo>()
  val b = koin.get<Repo>()
  println("single shared: " + (a.client === b.client))
  println("factory shared: " + (a.formatter === b.formatter))

  // Settings was never declared: nothing fails until it is requested
  println("startup finished")
  try {
      koin.get<Settings>()
  } catch (e: NoDefinitionFound) {
      println("crash when Settings opens: " + e.message)
  }
}

Expected output:

single shared: true
factory shared: false
startup finished
crash when Settings opens: No definition found for Settings

In production

The missing definition crash
  • Crash reports spiked on the Settings screen after a release; the stack trace ended in NoDefinitionFoundException for SettingsRepository.
  • A developer had added SettingsRepository as a constructor parameter of SettingsViewModel but never declared it in a module.
  • The app compiled and every other screen worked, so manual QA, which did not open Settings, missed it.
The fix
  • They added singleOf(::SettingsRepository) to the data module and shipped a hotfix.
  • They added a JVM unit test that calls verify() on every Koin module, so a definition whose constructor needs an undeclared type fails CI.
  • New ViewModels are declared with viewModelOf(::X) instead of hand-written lambdas, so the constructor and the definition cannot drift apart.
Flaky tests after adding Koin
  • After adding Koin, unit tests passed one at a time but failed in a full run with "A Koin Application has already been started".
  • Each test class called startKoin in @Before and never stopped it, so the global context from one test was still there in the next.
The fix
  • Test classes now use KoinTestRule.create { modules(testModule) }, which starts Koin before each test and stops it after.
  • ViewModel and repository unit tests stopped using Koin at all: they call constructors with fakes, which is faster and needs no global state.

Common mistakes

  • No verify() test. Without one, a missing definition is found by users. Add a verify() test per module, or use Koin Annotations / the compiler plugin for build-time checks.
  • Calling get() or inject() inside ordinary classes. The class now pulls from a global container, its constructor no longer shows what it needs, and tests must start Koin. Pass dependencies through the constructor and keep get() in module definitions.
  • Using single for everything. Every single lives as long as the container and shares its state with every caller. Use factory for cheap, stateless objects and single for expensive or intentionally shared ones.
  • Declaring a ViewModel with single or factory. It is then not stored in a ViewModelStoreOwner: factory creates a new instance on every recomposition or rotation, and single shares one forever. Use viewModel / viewModelOf.
  • Forgetting stopKoin() between tests. The next startKoin throws because a Koin application is already running. Use KoinTestRule or call stopKoin() in @After.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between Hilt and Koin?”

“Is Koin a dependency injection framework or a service locator?”

“How do you handle object lifetimes in Koin?”

“How do you make sure a Koin configuration is complete?”

Quiz

Which Koin definition creates a new instance every time the type is resolved?

A class is used in a constructor but has no Koin definition. When does the problem show up?

How should a ViewModel be declared in a Koin 4 module?

Which is the current way to check a Koin module in a unit test?

0 of 4 answered

Mini task

Task: Implement and verify a Koin module

  1. Create an interface ApiService with fun fetchData(): String, and RealApiService that returns "Data from API".
  2. Create class DataRepository(private val api: ApiService) with fun load(): String = api.fetchData().
  3. Write val appModule = module { singleOf(::RealApiService) { bind<ApiService>() }; factoryOf(::DataRepository) }.
  4. In a main function, call startKoin { modules(appModule) }, get the repository with KoinPlatform.getKoin().get<DataRepository>(), print load(), then call stopKoin().
  5. Write a JUnit test that calls appModule.verify(). Then remove the bind<ApiService>() part and run the test again.

Done condition: main prints Data from API, the verify test passes with the full module, and it fails with a message naming ApiService once the binding is removed.

Next: WorkManager