https://kotlinlang.org logo
#android
Title
# android
e

Eugen Martynov

09/02/2019, 5:52 AM
How do you people deal with LiveData nullability? I used it for data binding but it never nulls
m

Matej Drobnič

09/02/2019, 6:13 AM
I made this little extension method that I use everywhere:
Copy code
inline fun <T> LiveData<T>.observeNotNull(
    lifecycleOwner: LifecycleOwner,
    crossinline method: Function1<T, Unit>
) {
    observe(lifecycleOwner, Observer {
        if (it != null) {
            method(it)
        }
    })
}
and then I always call
.observeNotNull
not
observe
e

Eugen Martynov

09/02/2019, 6:43 AM
Thanks! What about when you call
value
?
m

Matej Drobnič

09/02/2019, 7:27 AM
I never do that.
👍 1
But I guess you can do
val value = liveData.value ?: error ("X should be non-null")
if you are sure it cannot be null