Use MediatorLiveData To Query And Merge Multiple Data Source Type Into Single LiveData (Kotlin)
April 13, 2018Assuming I need to fetch a list of Password
and Category
, merging them into a single LiveData
.
First, I create a Sealed Classes to represent both data type.
sealed class MergedData
data class PasswordData(val passwordItems: List<Password>): MergedData()
data class CategoryData(val categoryItems: List<Category>): MergedData()
Then I create a MediatorLiveData to fetch both data type.
fun fetchData(): MediatorLiveData<MergedData> {
val liveDataMerger = MediatorLiveData<MergedData>()
liveDataMerger.addSource(passwordDataSource.fetchAll(), {
if (it != null) {
liveDataMerger.value = PasswordData(it)
}
})
liveDataMerger.addSource(categoryDataSource.fetchAll(), {
if (it != null) {
liveDataMerger.value = CategoryData(it)
}
})
return liveDataMerger
}
Lastly I observe the LiveData
and make sure both data sets are received before processing.
val liveData = fetchData()
var passwordItems: List<Password>? = null
var categoryItems: List<Category>? = null
liveData.observe(activity, object : Observer<MergedData> {
override fun onChanged(it: MergedData?) {
when (it) {
is PasswordData -> passwordItems = it.passwordItems
is CategoryData -> categoryItems = it.categoryItems
}
if (passwordItems != null && categoryItems != null) {
// both data is ready, proceed to process them
// stop observing
liveData.removeObserver(this)
}
}
})
- 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