Search code examples
androidfirebaseandroid-fragmentsandroid-navigationandroid-architecture-navigation

SharedViewModel between the scope of a fragment


I have two fragment that should share a viemodel

class FragmentA(): Fragment() {
  val sharedViewModel = ViewModelProvider.(need_a_shared_context)....//not the activity context
}

class FragmentB(): Fragment() {
val sharedViewModel = ViewModelProvider.(need_a_shared_context).... //not the activity context
}

now, inside each fragment I need to access a shared viewmodel but not a sharedviewmodel hosted by the activity containing these fragments, because I'm working with Firebase and I have a listener sending data to my app.

So, If I attach the viewmodel to the activity lifecycle, I can share data between these two, but, it will be also listening for data when I'm not in FragmentA() or FragmentB()

Is there a way to scope the creation of this sharedviewmodel when I'm only at FragmentA() or FragmentB() ?

Edit

Since I'm using NavigationComponents, when I navigate from FragmentA() to FragmentB() , fragment A dies, so , If I create there my sharedviewmodel, it will die when I access FragmentB() and FragmentB() will generate a new instance of the viewmodel.


Solution

  • The question is kinda too wide.

    Why don't u want the activity to host the viewmodel? If you dont want your listeners to be notified while not actually displaying the UI, you can remove it [listeners]. I do not know exactly about Realtime Database (sure it has same features), but Firestore's addSnapshotListener methods return ListenerRegistration object, which has a remove() method to remove the listener, so you are not notified about the document updates and thus not charged for it.

    You can host the ViewModel by any component you want, but I would even consider using Object for it, so every instance of your ViewModel gets the same singleton, which stores the cached value and exposes it in the form of LiveData to your observers, but actually starts and stops observing the Firebase node (and updating the LiveData your fragments observe) only after specific methods get called - onStartObserving()/onStopObserving, which can be called from your fragments' onStart() & onStop()