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()) }
}
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 withgetViewModel()
rather thanget()
. See https://insert-koin.io/docs/reference/koin-android/viewmodel#viewmodel-api---java-compat