I want to use LiveData with Kotlin and have values that should not be null. How do you deal with this? Perhaps a wrapper around LiveData? Searching for good patterns here .. As
This is my solution.
class NotNullLiveData
constructor(private val default: T) : MediatorLiveData() {
override fun getValue(): T {
return super.getValue() ?: default
}
override fun setValue(value: T) {
super.setValue(value)
}
}
@MainThread
fun mutableLiveDataOfNotNull(initValue: T): NotNullLiveData {
val liveData = NotNullLiveData(initValue)
liveData.value = initValue
return liveData
}
@MainThread
fun mutableLiveDataOf(initValue: T): MutableLiveData {
val liveData = MutableLiveData()
liveData.value = initValue
return liveData
}
fun LiveData.toNotNull(default: T): NotNullLiveData {
val result = NotNullLiveData(default)
result.addSource(this) {
result.value = it ?: default
}
return result
}