I found a case when architecture components ViewModel
isn\'t retained - in short it goes as follows:
ViewModel
in
AFAIK, ViewModel
's only purpose is to survive and keep the data (i.e. "save the state") while its owner goes through different lifecycle events. So you don't have to "save the state" yourself.
We can tell from this that it's "not normal behavior". onCleared()
is only called after the activity is finished (and is not getting recreated again).
Are you creating the ViewModel
using the ViewModelProvider
, or are you creating the instance using the constructor?
In your activity, you should have something like:
// in onCreate() - for example - of your activity
model = ViewModelProviders.of(this).get(MyViewModel.class);
// then use it anywhere in the activity like so
model.someAsyncMethod().observe(this, arg -> {
// do sth...
});
By doing this, you should get the expected effect.