LiveData to the next level with MediatorLiveData and Transformations

Eddie eddie
The OOZOU Blog
Published in
2 min readDec 7, 2018

MediatorLiveData and Transformations seem to be very useful classes if we would like to do a ‘reactive patterns’ with LiveData and here are what I can show to you:

MediatorLiveData

From its explanation, it is a subclass of liveData which can ‘observe’ other LiveData and trigger onChanged() method when observed LiveData’s value is changed.

From the sample code above, when source’s value is changed, the onChanged method of Observer will be triggered.

Transformations

This class is way more like an utilisation of MediatorLiveData. It contains only 2 methods which are map() and switchMap()

These 2 methods doing the same thing which apply a function on the value stored in the LiveData object, and propagates the result downstream but the switchMap(), the function that passed in must return a LiveData object.

I’ve created a sample project here. You can take a look and stay with me to let me explain how the code works.

I use https://jsonplaceholder.typicode.com/ as a test api with /todos/1 endpoint. There is a created model name Todo to match with the response

There are 2 more classes for handling responses from api.

The ResponseResult will have 2 properties, both are a LiveData, one is for the response, the other one is for the error (ResponseError).

According to the Google suggestion, I made a repository module with will take a responsibility to fetch a data from network. In this module, I did some trick with ResponseResult:

The function getTodos() will return ResponseResult<Todo>, its 2 properties, data’s value will be updated when response is finished, and error’s value will be updated when error happened.

By following the SOLID guideline, I keep my Usecase class so simple.

Chaining LiveData

Let’s have a look at my ViewModel and Fragment class:

I triggered a LiveData (SingleLiveEvent) at onActivityCreated(), and if you take a look at line 18, Transformation.map() is called which mean getTodoUsecase() will be called. After fetching is done, responseResult will be assigned. And if you take a look again at line 22 and 26, Transformation.switchMap() are called which means when the responseResult’s value is updated, todoResult and errorResult instances will be pointed to the same instances as responseResult’s properties.

Tips: OnChanged() method will not be called if MediatorLiveData is not observed at anywhere.

Reference:

https://stackoverflow.com/questions/47575961/what-is-the-difference-between-map-and-switchmap-methods

--

--