https://insert-koin.io/docs/setup/koin/#koin-bom
implementation(platform("io.insert-koin:koin-bom:$koin_version"))
implementation("io.insert-koin:koin-android")
implementation("io.insert-koin:koin-core-coroutines")
implementation("io.insert-koin:koin-androidx-workmanager")
- Create application class annotation. We will use this in the last step.
class BaseApplication: Application() { override fun onCreate() { super.onCreate() } }
- Add to manifest.
<manifest ... > <application android:name=".BaseApplication" ... > ... </application> </manifest>
- An API class that will be injected in a repository.
class MyApi() { fun callNetwork() }
- A repository interface and its implementation that will be injected in a viewmodel.
interface MyRepo { fun doNetworkCall() } class MyRepoImpl( private val myApi: MyApi ): MyRepo() { override fun doNetworkCall() { myApi.callNetwork() } }
- A viewmodel to be injected in an activity.
class MainViewModel( private val repo: MyRepo ): ViewModel(){ fun doNetworkCall(){ repo.doNetworkCall() } }
Create a file AppModule.kt
.
val appModule = module { single { // create MyApi using Retrofit or something else Retrofit.Builder() .baseUrl("https://something") .addConverterFactory(MoshiConverterFactory.create()) .build() .create(MyApi::class.java) } // OLD //single<MyRepo> { // Provide an implementation of MyRepo. // "get()" will automatically fetch the api from above "single" block. MyRepoImpl(get()) //} singleOf(::MyRepoImpl) { bind<MyRepo>() } viewModel { // Notice different block for viewmodel MainViewModel(get()) } }
class MainActivity: ComponentActivity() {
private val viewModel: MainViewModel by inject()
}
In this example we inject MyApi
just for representation.
class MainActivity: ComponentActivity() {
//...
private val api: MyApi by inject()
}
class BaseApplication: Application() { override fun onCreate() { super.onCreate() startkoin { androidContext(this) modules(appModule) } } }
Done !