MVVM: Why the ViewModel is always recreated when Activity rotated

365 views Asked by At

My setup is: java Activity getting a ViewModel using Koin. All good with this, but when I rotate a phone, the ViewModel is always recreated. So how to avoid ViewModel recreation in the case? Thanks.

Activity:

private final FlowViewModel viewModel = get(FlowViewModel.class); 

Koin:

val appModule = module {
     ...
     viewModel { FlowViewModel(get()) }
}
1

There are 1 answers

1
laalto On BEST ANSWER

You're injecting the viewmodel as a regular object with get() and not as a viewmodel. It does not get any viewmodel special treatment.

To use koin-managed viewmodels in java, you can add the library io.insert-koin:koin-android-compat and access viewmodels in koin graph with getViewModel() rather than get(). See https://insert-koin.io/docs/reference/koin-android/viewmodel#viewmodel-api---java-compat