Search code examples
androidviewmodelandroid-lifecycle

Android - Jetpack - Make lazily created class lifecycle aware


Got an interesting case to solve.

Backstory

I have a ViewModel that is a LifecycleObserver, I'm following a nice architectural pattern where this VM is serving the overall screen logic, and is composing smaller VMs inside to serve components that are on screen.

In order to make these smaller VMs work out of the box, I make them lifecycle aware on the onCreate of the container ViewModel.

override fun onCreate(owner: LifecycleOwner) {
    super.onCreate(owner)
    smallerVMs.forEach(owner.lifecycle::addObserver)
}

Problem

However, I have n other small VMs that I will instantiate on demand, depending on an API call.

Because I don't have reference of them until they're instantiated, I can't make them lifecycle aware on onCreate as mentioned above.

And when the API is back with results, and I do instantiate them, I don't have a hold of the LifecycleOwner instance!

I thought of caching the LifecyclerOwner in onCreate, but that means keeping reference to the View in a VM, which is not a good practice in MVVM.

Any thoughts on this? Thanks in advance!

Disclaimer: Having the smaller VMs inside the big VM is essential, as the smaller VMs are reusable presentation pieces across the whole app


Solution

  • Instead of having every single child object observe the same life cycle owner, you should delegate since you're employing Composite pattern:

    Assuming you're using LifecycleEventObserver (since LifeCycleObserver should not be used directly):

    override fun onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        smallerVMS.forEach { it.onStateChanged(source, event) }
    }
    

    Then it doesn't matter when the child VMs are created - as long as they're in that list they'll get every callback when the parent does, as if they were observing themselves.