I'm developing an application based on Koin DI (ver : 1.0.1) with 2 modules(:app and :network). I have a requirement in :network module to have "Context". Below is how I implemented:
**Module**:
val appModule = module {
viewModel { LoginViewModel(get()) }
}
**Activity**:
private val viewModel by viewModel<LoginViewModel>()
**ViewModel**:
class LoginViewModel(val context: Context): ViewModel() {
...
// Send "context" to network class in :network module
...
}
Question: Is there any way we can directly send context to network class in :network module?
Both answers by @Rajat and @Andrey are correct. In fact if you look at the sources, you will see that androidContext()
is just an extension function to get()
, so these 2 definitions are identical:
val appModule = module { viewModel { LoginViewModel(get()) } }
...
val appModule = module { viewModel { LoginViewModel(androidContext()) } }
Answering your question, since get()
and androidContext()
are members of the module
DSL object, you could do this:
val networkModule = module { single { Network(androidContext()) } }
Or simply (I prefer this one for brevity):
val networkModule = module { single { Network(get()) } }
Application context is available inside a module through the function androidContext()
.
val appModule = module {
viewModel { LoginViewModel(androidContext()) }
}
This should solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With