Search code examples
androidandroid-architecture-componentsandroid-viewmodel

Creating my own ViewModelStore to control ViewModel lifecycle


It is stated in google example that to communicate from fragment to fragment, you could use the ViewModel scoped to the Activity. The problem with this approach is that, then the ViewModel will last until the Activity is destroyed.

In a Single Activity Application, this means that the activity will be littered with ViewModels which might not be needed anymore. You will also have problem with states if these ViewModels won't be cleared properly.

So I look around at how to alter the lifecycle of the ViewModel so that I doesn't have to be tied to the Activity lifecycle but be longer than the lifecycle of a Fragment. This will then be very useful for Multi-step / Transactional flow of screens where the requirements are filled-up during the screen flow process.

So basically, I would want a ViewModel to be scoped less than the activity but longer than a fragment.

To accomplish this, I created my own ViewModelStore and persist it across configuration the same way FragmentActivity persist its own ViewModelStore. Then when initializing the view model I will use,

ViewModelProvider(myCustomViewModelStore, myFactory).get(SomeViewModelClass::class.java)

Since the ViewModel is not scoped to my custom ViewModelStore, I could easily call viewModelStore.clear() to control the lifecycle of the ViewModel.

I was wondering whether this is a good idea and whether someone out there is using the same idea.

Thanks in advance!


Solution

  • As of Navigation Component 2.1.0-aplha02, ViewModels can now be scoped to transaction flows through the Navigation Component navigation graph.