Saul
Saul

Reputation: 119

Inject String parameter into ViewModel from Compose using Koin

As the title says I want to inject two string params into my ViewModel from my Compose Activity using Koin. And I don't want to create a Factory ViewModel.

I saw how to inject Objects but I'm confused when it comes to parameters. This was so simple using Dagger Hilt I feel stupid for asking this..Any tips please?

I call this from the compose activity

    val someViewModel: SnapshotViewModel by viewModel {
    parametersOf(displayName, securityName)
}

and in my Koin Module I do this but I get an error

Too many arguments for public constructor

val module = module {
single { params -> SnapshotViewModel(params.get<String>(), params.get<String>())}}

And here I try to inject them in my ViewModel

private val displayName: String by inject()
private val securityName: String by inject()

Upvotes: 0

Views: 3166

Answers (1)

Haroun SMIDA
Haroun SMIDA

Reputation: 1116

No need to call by inject() in your property definitions. Either you pass the values via constructor or via injection

Option 1:

  • Create a constructor for your view model
class SnapshotViewModel(displayName: String, securityName: String)
  • Then define property instance in the module
val module = module {
    single { params -> 
        SnapshotViewModel(params.get<String>(), params.get<String>())
    }
}

or

val module = module {
    single { (displayName: String, securityName: String) -> 
        SnapshotViewModel(displayName, securityName)
    }
}

Option 2:

  • Add the property definitions as follow, assuming your view model is tagged with KoinComponent
private val displayName: String
    get() = getKoin().getProperty("displayName", "defaulValue")
private val securityName: String 
    get() = getKoin().getProperty("securityName", "defaulValue")
  • Then set the property values before initializing the view model. Depending where you set the value, you may need to tag the class with KoinComponent in order to have access to getKoin()
getKoin().setProperty("displayName", "Value")
getKoin().setProperty("securityName", "newValue")

Upvotes: 0

Related Questions