MediatorLiveData to the Rescue
Exploring LiveData features
Let’s say we have a ViewModel
that exposes a LiveData<List<Book>>
that comes from Room, and our view observes it and updates the list of books accordingly. That’s simple, beautiful, and works great.

Now let’s say our app allows the user to change the order of the list:

How do we implement that? Right now the view only observes one single LiveData
, and we want to stick with that because single streams FTW. We have no control over the LiveData
Room gives us, so how do we make the same LiveData
emit the list of books in a different order? Remember, we want to make sure we expose a single stream to our view.
We could update the database with the different order we want, so Room would naturally emit the books in the new order. That makes sense, but if we're not interested in persisting the new order, that’s just overkill. The way to go here is called MediatorLiveData
:
LiveData subclass which may observe other LiveData objects and react on OnChanged events from them.
With a MediatorLiveData
, we’re able to react to books emitted by Room, and we’re also able to update its value (just like we’d do with a MutableLiveData
). Here’s how the code would look like:
Now our view can continue listening to a single stream of data (yay!), and whenever it calls viewModel.rearrangeBooks()
, the same stream will emit a new list with the new order.
Normally, we’d expose our MediatorLiveData
as a LiveData
just so its API doesn't leak to the view — that hasn't been done here just to keep the examples shorter and simpler.
We're not sorting the books in the database level here because that's how things worked in the situation I found myself into and got the inspiration to write this blogpost. However, it's definitely possible to have two different LiveData
coming out of our BookDao
and use the MediatorLiveData
to… mediate them! Here's how it'd look like:
That actually makes the MediatorLiveData
look more like a mediator, and matches more closely what is presented about it in the LiveData
overview. And in the end we're still exposing a single LiveData
to the view just like we did before.
When we're in a ViewModel
, we don't want to observeLiveData
instances (and we can't because we have no LifecycleOwner
around). However, we might want to react to them, or even combine (and mediate) multiple LiveData
objects. For those situations, MediatorLiveData
is what we're looking for.
LiveData
is still a new component, but there’s already many interesting non-obvious features around it like our MediatorLiveData
and Transformations
, for instance. Make sure you explore them all so you’re ready to make the right call when writing awesome reactive code with it!
Edit: a couple days after I posted this, Jose Alcérreca wrote a great article that dives deeper beyond the basics of LiveData
, make sure you check it out!