Search code examples
androidkotlincode-injectionkoin

Android Koin injected viewmodel with multiple same class parameters fails


I'm following the docs as stated her https://insert-koin.io/docs/reference/koin-android/viewmodel/#viewmodel-and-injection-parameters

The only difference is my viewmodel has 2 (besides Koin injected repos) parameters of the same class String. Lets call them stringA = "red" and stringB = "blue".

When I pass the parameters these are clearly defined differently. But when the viewmodel is instantiated, I log the strings and both have the value of stringA, "red".

I can wrap them both into a data class, but ideally I would want them separately, any idea of what is wrong or what should be done?

Koin Module

val viewModelsModule = module {

  viewModel { params ->
    MyViewModel(get(), stringA = params.get(), stringB = params.get(), get()) }

}

ViewModelInjection

  val viewModel: MyViewModel = getViewModel(parameters = {parametersOf("red", "blue")})

Parameter check inside MyViewModel

init {
    viewModelScope.launch {
      Log.d("TAG", "$stringA $stringB")
    }
  }

and print:

red red

Solution

  • params.get() resolves the parameters by type. Since both are strings, it will match the first one in both cases. It works implicitly only if the types are different (e. g. int and String).

    The solution is to index the parameters instead: stringA = params[0], stringB = params[1]

    Longer snippet for context:

    viewModel { params ->
        MyViewModel(get(), stringA = params[0], stringB = params[1], get()) }