Home » Android » android – Sharing Data between ViewModels

android – Sharing Data between ViewModels

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a complex screen in my project which I’m breaking in more than one fragment. I’m trying to follow the MVVM architecture for these classes, so which fragment has its own ViewModel and Contract class.

The issue is that all the ViewModels needs the same object instance (let’s call it Book) to do Room transactions.

Does it have a correct way to share data (or LiveData) between ViewModels? I know the concept of Shared ViewModel but I don’t know if I can apply it to this case. I also thought about using MediatorLiveData but didn’t get a good approach on it too.

I’m thinking about having a class (let’s call BookObservableProvider) with a LiveData<Book> (or Rx Subject<Book>) where each ViewModel injects the same instance and load/update always the same value.

Is it a good approach?

How to&Answers:

In my personal opinion your approach is not bad for this situation, but if want to try something else, I can advise you RxBus method. Here is a great article about it. With this approach you can simply publish data in activity, which holds fragments, and then listen to this particular event in all your fragments.

Something like :

//Activity
RxBus.publish(RxEvent.EventOnBookProvide(bookObject)

and

//Fragment
RxBus.listen(RxEvent.EventOnBookProvide::class.java).subscribe {
        useObject(it)
    }

And don’t forget to use Disposable and .dispose() it in onDestroy() if using Activity and onDestroyView() if using fragment.

Answer:

You should share those data between fragments/activities (maybe using Intents for activities) , and than handle those data by the other ViewModel