--

I took some time today to create a proof-of-concept gist for a CompositeLifecycleOwner:
https://gist.github.com/cbeyls/86f18a64b44fff51bc02ff6f82606923

And an extension to add a custom property on any ViewModel so you don't have to inherit from a custom class:
https://gist.github.com/cbeyls/7774eb41f42c755112d69ce2c472d4aa

In the Activities and Fragments you register the Lifecycle like this:
viewModel.lifecycleOwner += viewLifecycleOwner

It will be unregistered automatically when it hits the destroyed state so there will be no memory leak.

Then in your ViewModel you can make specific flows pause along with the global lifecycle using:
flow.flowWithLifecycle(lifecycleOwner.lifecycle).distinctUntilChanged()

I think this is an interesting way to make Flows more ViewModel-friendly. Not sure I would recommend it as a general solution though.

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

Responses (1)