Please notice that this issue is not systematic unlike other reported issues on StackOverflow.
I have a ViewModel that takes some parameters:
class MyViewModel(
private val refreshTokenUseCase: RefreshTokenUseCase,
...
) : BaseViewModel() {
And a factory:
class MyViewModelFactory(
private val refreshTokenUseCase: RefreshTokenUseCase,
...
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MyViewModel(refreshTokenUseCase, ...) as T
}
}
and I create the ViewModel in the onCreate
of the Activity
:
val myViewModel: MyViewModel by viewModels {
MyViewModelFactory(refreshTokenInteractor)
}
model = myViewModel
in the onCreate
of the Fragment
I have:
val viewModel: MyViewModel by activityViewModels()
model = viewModel
Very randomly on Crashlytics I see crashes:
Caused by java.lang.InstantiationException: java.lang.Class<com.my.package.MyViewModel> has no zero argument constructor
I don't understand why the factory does not work and why a crash like this is not repeatable: it happened only once in 1 week and I have never managed to reproduce it running the app.
Do you see something wrong with the code?
One thing to add is that the crash always happens in the Fragment
that gets the instance of the ViewModel
that is supposed to have been created by the Activity
. So the crash is on the line:
val viewModel: MyViewModel by activityViewModels()