Chain Android Livedata With Transformations
March 11, 2018When 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.
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn