Koin: Android app crash due to org.koin.core.error.InstanceCreationException

Created on 25 Feb 2020  路  2Comments  路  Source: InsertKoinIO/koin

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()
android question

Most helpful comment

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"
        )
}

All 2 comments

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() ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guymclean picture guymclean  路  3Comments

erikhuizinga picture erikhuizinga  路  3Comments

hkelidari picture hkelidari  路  3Comments

AHarazim picture AHarazim  路  3Comments

CristianMG picture CristianMG  路  3Comments