A LiveData class that has null
value.
The LiveData implementation that can represent empty results:
class AbsentLiveData<T : Any?> private constructor() : LiveData<T>() {
init {
// use post instead of set since this can be created on any thread
postValue(null)
}
companion object {
fun <T> create(): LiveData<T> {
return AbsentLiveData()
}
}
}
Usage
val someLiveData: LiveData<Any> =
Transformations.switchMap(myTrigger) {
if (it != null) {
repository.getSomeLiveData()
} else {
AbsentLiveData.create()
}
}