Using the new Navigation Architecture Component, I've got a single activity as a navhost with multiple fragments for my screens. Right now I have an EditProfileFragment where the user can click a button and another fragment opens, with a list of countries to choose from. Let's say I want to share the result of that country selection back to the EditProfileFragment. The general idea is that I'll have a single EditProfileViewModel for all "edit profile" actions.
How do I share the selected country between those fragments? I'm thinking using a shared viewmodel, but I'm hesitant scoping it to the activity because I don't want it to persist when the user completes the "edit profile" flow.
Are there any other clean/recommended approaches I should consider? Maybe a singleton that temporarily holds that value?
TL;DR: We can pass parameters to our ViewModel, use it as a data holder, also to share data between Fragments, and to persist its state across process recreation. This is part of a multi-part series regarding Advanced ViewModels on Android. This post focuses on how our ViewModel can be shared between Fragments.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
By passing getActivity instead of “this” to the ViewModelProviders. of method, we can scope the lifecycle of this ViewModel to the activity instead of the fragment, and this way access it from multiple different fragments to share data between them, as long as their activity is alive.
The lifecycle of a ViewModelThe ViewModel remains in memory until the ViewModelStoreOwner it's scoped to goes away permanently: In the case of an activity, when it finishes.
It's easier with a shared view model indeed, but as you said, it comes with other concerns like scoping the view model to a higher context for simple information exchange.
IMHO shared view model is not a bad approach in certain scenarios. I was working on an app which has 5 tabs, first tab was like a summary of 2nd and 3rd ones. It was a good choice to use shared view model, since I was just reusing the data, just changing the number of items adapter shows in corresponding views, logic was being reused.
It sounds like you have common logic / items in your profile & profile edit page. I don't know how many, but if you feel like it's not enough to share a view model between these two, remember just because you are using view models doesn't mean you have to use them to share / store / pass around some data. For example :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With