33

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?

user2064275
  • 332
  • 1
  • 3
  • 8

4 Answers4

62

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()) }
}
kevoroid
  • 5,052
  • 5
  • 34
  • 43
maslick
  • 2,903
  • 3
  • 28
  • 50
16

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

BenjyTec
  • 1,719
  • 2
  • 12
  • 22
nyarian
  • 4,085
  • 1
  • 19
  • 51
7
val appModule = module {
    viewModel { LoginViewModel(androidContext()) }
}

This should solve your problem.

Rajat Beck
  • 1,523
  • 1
  • 14
  • 29
1

Other way to inject context is using Constructor DSL of Koin:

val appModule = module {
    viewModelOf(::LoginViewModel)
}
N-JOY
  • 10,344
  • 7
  • 51
  • 69