Autowire DSL for Android
This guide covers Android-specific autowire DSL extensions. For core autowire DSL concepts (singleOf, factoryOf, scopedOf), see Autowire DSL.
info
Naming Note: This feature was previously called "Constructor DSL" in earlier documentation. Both terms refer to the same capability.
Android-Specific Keywords
In addition to the core autowire DSL keywords, Koin provides Android-specific keywords for common Android components:
viewModelOf()- equivalent ofviewModel { }- declare a ViewModelfragmentOf()- equivalent offragment { }- declare a Fragment (when using Fragment Factory)workerOf()- equivalent ofworker { }- declare a WorkManager Worker
Complete Example
Given an Android application with the following components:
// A simple service
class SimpleServiceImpl() : SimpleService
// a Presenter, using SimpleService and can receive "id" injected param
class FactoryPresenter(val id: String, val service: SimpleService)
// a ViewModel that can receive "id" injected param, use SimpleService and get SavedStateHandle
class SimpleViewModel(val id: String, val service: SimpleService, val handle: SavedStateHandle) : ViewModel()
// a scoped Session, that can received link to the MyActivity (from scope)
class Session(val activity: MyActivity)
// a Worker, using SimpleService and getting Context & WorkerParameters
class SimpleWorker(
private val simpleService: SimpleService,
appContext: Context,
private val params: WorkerParameters
) : CoroutineWorker(appContext, params)
we can declare them like this:
module {
singleOf(::SimpleServiceImpl){ bind<SimpleService>() }
factoryOf(::FactoryPresenter)
viewModelOf(::SimpleViewModel)
scope<MyActivity>(){
scopedOf(::Session)
}
workerOf(::SimpleWorker)
}
Android Reflection DSL (Deprecated since 3.2)
caution
Koin Reflection DSL is now deprecated. Please use Koin Autowire DSL above