Search code examples
androidkotlinandroid-architecture-componentsandroid-livedata

How can I share LiveData between multiple ViewModels?


I've tried extracting the value into a base class and having the ViewModels extend it. When I do that, however, the Observer isn't sticking to the LiveData. For instance, when I have a parent class with LiveData:

class Base : ViewModel() { 
    private val _ data = MutableLiveData()
    val data: LiveData = _data

    fun someEvent(foo: Foo) { // update _data }
}

class Derived : Base()

class Derived1 : Base()

Then get one of those ViewModels and observe data:

class Frag : Fragment {
    onViewCreated() {
        // get Derived, ViewModelProviders.of ...etc
       derived.data.observe { // Doesn't observe changes }
    }
}

Calling Base.someEvent(foo) doesn't notify the LiveData in the Fragment.

I want to avoid getting a reference to both subclasses and invoking someEvent on each. One thing to note is that I'm using a single Activity approach and all ViewModels are Activity scoped.


Solution

  • class Derived : Base()
    

    and

    class Derived1 : Base()
    

    have their own instance of:

    private val _ data = MutableLiveData()
    val data: LiveData = _data
    

    that means you need to

    derived.data.observe { // do something }
    derived1.data.observer { // do something }
    derived.someEvent(someFoo)
    derived1.someEvent(someFoo)
    

    You are trying to achieve something in a wrong way.