This is a simple Android application that uses MVVM with
- Kotlin Koin for dependancy injection
- Retrofit for Network calls
- RxKotlin for thread management
Here are the steps taken to build an application using KOIN
In build.gradle app must have these
// Koin for Android
implementation "org.koin:koin-android:$koin_version"
// Koin Android Scope features
implementation "org.koin:koin-android-scope:$koin_version"
// Koin Android ViewModel features
implementation "org.koin:koin-android-viewmodel:$koin_version"
// Koin Android Experimental features
implementation "org.koin:koin-android-ext:$koin_version"
implementation "io.reactivex.rxjava2:rxjava:$rxjava_version"
implementation "io.reactivex.rxjava2:rxkotlin:$rxkotlin_version"
implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
implementation "com.squareup.retrofit2:converter-scalars:$retrofit_version"
Then make sure to have an Application class and add it into your manifest like KoinApplication.kt
For every module/viewModels/Factory, just add those in their respective module variables in KoinApplication.kt, if there are new viewModels say UserViewModel
val viewModelModules = module{
viewModel { UserViewModel(get(), get()) }
}
The get() parameters are for modules already injected and needed for the viewModel class, like the LoginViewModel.kt has 2 params which are already injected in the
val networkModules = module {
single{ AppModule()}
single { AppModule().provideGson() }
single { AppModule().provideOkHttpClientCredential(get()) }
single{ AppModule().provideGeneralService(get(),get())}
single{ AppModule().provideSchedulerProvider()}
}
Once the viewModel modules has been created, you can use them freely by injecting them with the by viewModel() keyword inside your activity. We call these lazy declaration.
val viewModel: LoginViewModel by viewModel()
In Koin there are 3 types of modules,
- single{} for singletons or instances. Invoke them with by inject()
- viewModel{} for viewModels. Invoke them with by viewModel()
- factory{} if you need new instance everytime. Invoke them with by get()