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
I don't know if this is the best solution but this is what I came up with and what I use:
class NonNullLiveData(private val defaultValue: T) : MutableLiveData() {
override fun getValue(): T = super.getValue() ?: defaultValue
fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
observe(owner, Observer {
body(it ?: defaultValue)
})
}
}
Creating the field:
val string = NonNullLiveData("")
And observing it:
viewModel.string.observe(this) {
// Do someting with the data
}