Home > front end >  MVVM: Why the ViewModel is always recreated when Activity rotated
MVVM: Why the ViewModel is always recreated when Activity rotated

Time:01-24

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

CodePudding user response:

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

  • Related