I've created this extension method for an androidx.lifecycle.LiveData
:
inline fun <T> LiveData<T>.observeNotNull(crossinline observer: (T) -> Unit) {
this.observe(viewLifecycleOwner, Observer { value ->
value?.let { observer(it) }
})
}
As you can see, the value passed to the observer parameter (it) can never be null. But when I call this method, the value is technically nullable, as shown in this example:
I'd like to do something like crossinline observer: (T!) -> Unit
, is this possible?
EDIT: the extension should work on both nullable and non-nullable livedata types. Preferably combined in 1 extension method, but ifit's only possible when using 2 separate extension methods I'd still like to hear.
CodePudding user response:
It depends on the concrete type that is represented by type variable T
if it
is nullable. If there is no further information to infer the concrete type, it is Any?
, and thus it
can be null. You have to define T: Any
if you want to ensure that T
represents a non-nullable type:
inline fun <T: Any> LiveData<T>.observeNotNull(crossinline observer: (T) -> Unit) {
this.observe(viewLifecycleOwner, Observer { value ->
value?.let { observer(it) }
})
}
If you want to allow all types for T
, but not for the argument of observer
, then this should be possible to achieve with definitely non-nullable types in Kotlin 1.7 using notation T & Any
:
inline fun <T> LiveData<T>.observeNotNull(crossinline observer: (T & Any) -> Unit) {
this.observe(viewLifecycleOwner, Observer { value ->
value?.let { observer(it) }
})
}