Chain Android Livedata With Transformations

March 11, 2018
When one LiveData need to wait for result from another LiveData

In this example, I need to load List<Place> based on Location.

val locationLiveData: LiveData<Location> = viewModel.fetchLocation()
val placesLiveData: LiveData<List<Place>> = Transformations.switchMap(locationObserver, { location ->
    if (location != null) {
        viewModel.fetchAllPlaces(location)
    }
})
placesLiveData.observeOnce(this, Observer<List<Place>> { places ->
    if (places != null) {
        // do something: load places into UI
    }
})

Assuming you want to do some processing with Location, you can observe Location as well.

val locationLiveData: LiveData<Location> = viewModel.fetchLocation()
val locationObserver = Observer<Location> { location ->
    if (location != null) {
        // do something: update location to UI
    }
}
locationObserver.observe(this, locationObserver)
val placesLiveData: LiveData<List<Place>> = Transformations.switchMap(locationObserver, { location ->
    if (location != null) {
        // if you don't want to observe location, you can do your location processing here as well.
        viewModel.fetchAllPlaces(location)
    }
})
placesLiveData.observeOnce(this, Observer<List<Place>> { places ->
    if (places != null) {
        // do something: load places into UI
    }
})

NOTE: the characteristic of attaching an observer to locationLiveData is that you can stop observing placesLiveData and still keep locationLiveData running.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.