I create viewmodel in MainFragment:
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
...
}
When user select item then navigate to Details fragment, this transaction is added to backstack.
getFragmentManager()
.beginTransaction()
.replace(R.id.root, Details.newInstance())
.addToBackStack(null)
.commit();
When user press back in Details fragment, everything is ok, but if user rotate device in Details fragment and press back then:
- new instance of ViewModel is created for MainFragment
- old instance is still alive ( method onCleared not called)
Is this a bug in ViewModelProviders? How to fix this? In my opinion ViewModel should be restored.