onCreate() used to display list of data for example listX and there is 3 nav tabs (X,Y,Z)onCreate() called again it will listX while nav is selected on Y or Z which is wrong to User.onCreate() load lists based on saved stateList<User>()) and is filled at runtime with method addUser().ViewModel and addUser() be at ViewModel.when activity is destroyed there two possible expectation from user
finish().in case of fully destroy of activity, ViewModel fails to maintain state.
Solution: save state at onSaveInstanceState(outState:Bundle?) and at onCreate() get that state and store it at ViewModel
This technique used to have a durabale persisitance.
list of real objectsas we knew that VM will be destroyed also and it is not effiecent to store real objects into bundle so IDEA is to save IDS or info that help to restore that list from DataStore in app then use these ids (will be stored in bundle) to restore objects from DataStore.
isFirstCreatedVM = true field at VM and at oc we set it falseclass MyVm:viewModel(){ var isFirstCreatedVM = false } class View { onCreate(bundle:Bundle?){ if (viewmodel.isFirstCreatedVM && bundle != null ){ viewmodel.restoreSaved(bundle) } viewmodel.isFirstCreatedVM = false } }
ViewModel will not be destroyed so no need to restore state as it is already mantained in itViewModel will be destroyed so isFirstCreatedVM be true as ViewModel is recreated and bundle be not null so now we can restore state.Lifecycle: some tasks(such as listen to location updates, call backend services) takes recources from android and needed to be cleared up so no leak occurs.
also logic of register and unregister to these taks should be done at LifecyclerObserver so Activity be for User Interface tasks.
so we will need two component
LifecyclerOwner: own lifecycle and publish his events (such as Activity/Fragment)
LifecyclerObserver: listen to lifecycle events
for LifecyclerObserver should implement LifecyclerObserver and use OnLifecycleEvent annotations with specify what event such as
@OnLifecycleEvent(Lifecycler.Event.ON_START) fun startHandler(){ // start yout work }
There are all events (ON_CREATE,ON_START, ON_RESUME, ON_PASUE, ON_STOP, ON_DESTROY)
Steps:
Observer by extend LifecyclerObserver and annotate your methods with EVENT typeLifecyclerOwner to that observer (Hint: Activity/Fragment has property called lifecycle this is LifecyclerOwner)lifecycler.addObserver(this)lifecycle.currentState property.atLeast(state) and send minimum state u want.