When is the viewmodel onCleared called

ir2pid picture ir2pid · Jun 22, 2018 · Viewed 25.9k times · Source

Are ViewModels independent of activity/fragment lifecycles or just their configuration changes. When will they cease to exist and the subsequent onCleared() method called. Can the viewModel be shared with another Activity ?

A situation:

Activity1+viewModel1--->(rotation)--->Activity1+viewModel1
--->(launch Intent)--->Activity2+viewModel1

is this sharing possible and is it a good practice.

Also, since the app lifecycle callbacks, onPause->onStop->onDestroy is same for both

1.activity rotating and

2.when an Activity ends,

how is a ViewModel figuring out internally the right time to call onCleared and finally end its lifecycle.


Findings:

the ViewModel uses a holderFragment internally to hold an instance of the activity and uses the setRetainInstance method like fragments to account for configuration changes.

Source: dive-inside-of-androids-viewmodel-architecture-components

enter image description here

Answer

Sagar picture Sagar · Jun 22, 2018

Are ViewModels independent of activity/fragment lifecycles or just their configuration changes.

ViewModels (VMs) are independent of configuration changes and are cleared when activity/fragment is destroyed.

Following is the lifecycle of ViewModel from official site:

ViewModel

Can the viewModel be shared with another Activity ?

You shouldn't do that with Activities. However fragments can share a ViewModel using their activity scope to handle communication between them

How is a ViewModel figuring out internally the right time to call onCleared and finally end its lifecycle?

A VM's onCleared is called when the app is put into the background and the app process is killed in order to free up the system's memory.

See the Do ViewModels persist my data? section from this Android Developer's post, ViewModels: Persistence, onSaveInstanceState(), Restoring UI State and Loaders

If you want the user to be able to put the app into the background and then come back three hours later to the exact same state, you should also persist data. This is because as soon as your activity goes into the background, your app process can be stopped if the device is running low on memory.

If the app process and activity are stopped, then the ViewModel will be cleared as well.