Christophe Beyls
2 min readNov 27, 2021

--

Thank you for your answer.

Your idea of moving the lifecycle to the ViewModel in order to only restart one part of the Flow instead of the entire one is interesting, I don't think I saw that before.

I agree that the Android ViewModel effectively has a Lifecycle: it is created with the first instance of an Activity or Fragment and destroyed with the last instance of it. This lifecycle is actually a superset of the Activities or Fragments lifecycle and it is not available in the form of an androidx.lifecycle.Lifecycle implementation. Technically, a LiveData inside a ViewModel also observes a Lifecycle when it is observed by the View so it makes sense.

The part I didn't like is the fact that unlike LiveData, your code only accounts for a single Lifecycle at a time and if you register a second one on the ViewModel while a previous Lifecycle is still active it won't work properly.

So it made me think that a more general solution would be to create a "Meta-lifecycle" implementation using a LifecycleRegistry, that would allow to aggregate multiple Lifecycles. This custom Lifecycle would start in the CREATED state, then move to the STARTED state when there is at least one child Lifecycle in the STARTED state (similarly to LiveData becoming active when there is at least one observer in the STARTED state). Finally it would move to the DESTROYED state when manually calling a destroy() method in ViewModel.onClear() for example.

That custom Lifecycle implementation could then be used in a ViewModel so you would be able to use the standard flowWithLifecycle() in the ViewModel. Each component connecting to the ViewModel would then have to register its lifecycle so it becomes part of the "meta-lifecycle".

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

Responses (1)