How to Inject application context from 'app' module to 'network' module using Koin DI

白昼怎懂夜的黑 提交于 2020-05-10 03:53:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!