Is there a ViewModel that gets cleared on Activity's onPause (going to background), What should I use instead?

531 Views Asked by At

I thought an AndroidViewModel with a FragmentActivity as storeOwner would be a good idea in order to:

  • Handle cross communication between Fragments;

  • Handle UI elements that persist Navigation changes(like a NavigationDrawer's menu or a Toolbar),

  • Handle a temporal cache for downloaded data (to prevent double download on Fragment creation/destruction)

    For example: Fragment's onCreateView()(Connects to DB) => Frag's onDestroy() (disconnects from cache, but remains connected to DB) => Frag's onCreateView() again (reconnects to cache)).

But most importantly:

  • Handles some degree of background DB listening, which means not as much as the likes of notification services which are able to survive app's going to the background, but also not as limited as being called exclusively by a view, meaning they need to be connected on App start.

The problem is that FragmentActivity()'s ViewModelStoreOwner does not get cleared(), ...never, If we provide ViewModels with a hypothetical LifeCycle of their own that begins on instantiation, and ends on onCleared(), and bound them to the the Activity's storeOwner they basically become a ... Service.

So before creating a custom ViewModelStoreOwner that handles/listens Activity's onStart() and onPause(), I am wondering if there may already be a component that does this (that I am not aware of), and how would this component be accessed through the different Fragments.

Now I am aware that Activities have a lifeCycle of their own, but If anyone thinks exposing absolutely every component just to access the Activity's LifeCycleOwner.... tbh I don't think that would be the best approach, the Activity class would become unreadable, crammed with unrelated functions.

0

There are 0 best solutions below