4

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
sgtpotatoe
  • 340
  • 6
  • 17
  • I've never used Koin but you seem to be passing the same value for `stringA` as you are for `stringB` to your ViewModel constructor – Ivan Wooll Dec 23 '21 at 10:22

1 Answers1

8

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()) }
Raimund Krämer
  • 1,255
  • 1
  • 11
  • 29
  • 1
    I am now using a data class as a more scalable solution, but this is exactly what I needed at the time, thanks! – sgtpotatoe Mar 30 '22 at 22:29