问题
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?
回答1:
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()) }
}
回答2:
Application context is available inside a module through the function androidContext().
回答3:
val appModule = module {
viewModel { LoginViewModel(androidContext()) }
}
This should solve your problem.
来源:https://stackoverflow.com/questions/53439111/how-to-inject-application-context-from-app-module-to-network-module-using-ko