Nullability and LiveData with Kotlin
You can create an extension for LifecycleOwner
fun <T> LifecycleOwner.observe(liveData: LiveData<T?>, lambda: (T) -> Unit) {
liveData.observe(this, Observer { if (it != null) lambda(it) })
}
and then in your fragment/activity
observe(liveData) { ... }
You can do this
normalLiveData
.nonNull()
.observe(this, { result ->
// result is non null now
})
There is an article about it. https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333
I little improve answer The Lucky Coder. This implementation cannot accept null values at all.
class NonNullMutableLiveData<T: Any>(initValue: T): MutableLiveData<T>() {
init {
value = initValue
}
override fun getValue(): T {
return super.getValue()!!
}
override fun setValue(value: T) {
super.setValue(value)
}
fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
observe(owner, Observer<T> { t -> body(t!!) })
}
override fun postValue(value: T) {
super.postValue(value)
}
}
I don't know if this is the best solution but this is what I came up with and what I use:
class NonNullLiveData<T>(private val defaultValue: T) : MutableLiveData<T>() {
override fun getValue(): T = super.getValue() ?: defaultValue
fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
observe(owner, Observer<T> {
body(it ?: defaultValue)
})
}
}
Creating the field:
val string = NonNullLiveData("")
And observing it:
viewModel.string.observe(this) {
// Do someting with the data
}