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: