I updated the koin library to the latest stable -
implementation "org.koin:koin-androidx-viewmodel:2.1.0"
I declare the viewModel in appModules as -
private val viewModelModules = module {
viewModel { (handle: SavedStateHandle) -> MyViewModel(handle, get()) }
}
I use it in MyActivity as -
private val viewModel: MyViewModel by viewModel {
parametersOf(
Bundle(),
"myViewModel"
)
}
And I get a crash -
java.lang.RuntimeException: Unable to start activity ComponentInfo: org.koin.core.error.InstanceCreationException: Could not create instance for [Factory:'com.example.view.viewmodel.MyViewModel']
Caused by: java.lang.ClassCastException: android.os.Bundle cannot be cast to androidx.lifecycle.SavedStateHandle
But removing saved state handle works?
If I remove the saved state handle meaning if I declare the viewModel in appModules as -
private val viewModelModules = module {
viewModel {MyViewModel(get()) }
}
And in MyActivity -
I use it in MyActivity as -
private val viewModel: MyViewModel by viewModel()
I use 2.1.0 where stateViewModel works ok.
You can try public SavedStateHandle() or public SavedStateHandle(@NonNull Map<String, Object> initialState)
private val viewModel: MyViewModel by viewModel {
parametersOf(
SavedStateHandle(),
"myViewModel"
)
}
Yes this works for me. Thanks @svrlopatrik . But interestingly why does the document still say to use bundle. What if I want to set arguments and retrieve it, can I still use public SavedStateHandle() ?
Most helpful comment
I use
2.1.0wherestateViewModelworks ok.You can try
public SavedStateHandle()orpublic SavedStateHandle(@NonNull Map<String, Object> initialState)