Search code examples
androidandroid-fragmentsandroid-architecture-componentsandroid-viewmodelandroid-architecture-navigation

Shared viewmodel between fragments, without scoping to the activity?


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.

  1. 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.

  2. Are there any other clean/recommended approaches I should consider? Maybe a singleton that temporarily holds that value?


Solution

  • Answering my own question on how I resolved this for future reference:

    Because I wanted to keep the 1-to-1 relationship between ViewModel-View(controller)/Fragment, I went with a UserRepository that holds a "temporary state" object for cases like this.