Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

koin

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?

like image 752
user2064275 Avatar asked Nov 22 '18 23:11

user2064275


3 Answers

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()) } } 
like image 175
maslick Avatar answered Oct 21 '22 22:10

maslick


Application context is available inside a module through the function androidContext().

like image 27
nyarian Avatar answered Oct 21 '22 22:10

nyarian


val appModule = module {
    viewModel { LoginViewModel(androidContext()) }
}

This should solve your problem.

like image 40
Rajat Beck Avatar answered Oct 21 '22 22:10

Rajat Beck