Chain Android Livedata With Transformations

Mar 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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.