LiveData from architecture components defines an Observer with nullable value for the receiver callback:
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(@Nullable T t);
}
Why is there an explicitly nullable annotation?
The doc of LiveData.observe()
also says:
If LiveData already has data set, it will be delivered to the observer.
E.g. Observer waits for non-nullable updates or immediately receive previous non-nullable value, that should hold especially in Kotlin, until I define T
as nullable.
The code seem to be working like that. I understand why this doesn't hold for LiveData.getValue()
, which may be called manually before first data is delivered (and checks therefore for mData != NOT_SET
to return a null).
So the second question is: Is is safe to assume the value is non-null in Kotlin when T is non-nullable?
Fixed in androix.lifecycle 2.0.0-beta01
.
Please report android Team if you encounter any issues.
Starting from 2.0.0-beta01
and later androidx.lifecycle
version the onChanged
parameter no longer contains @Nullable
annotation. The changes is due to the improvement request courtesy by the OP.
package androidx.lifecycle;
/**
* A simple callback that can receive from {@link LiveData}.
*
* @param <T> The type of the parameter
*
* @see LiveData LiveData - for a usage description.
*/
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(T t);
}
Is is safe to assume the value is non-null in Kotlin when T is non-nullable?
It depends, if you're the one who created the LiveData
subclass or plainly using the existing MutableLiveData
and you design it that it will never return null then it is safe to assume that it will never return null.
For the case that the LiveData
is implicitly created by not you especially those LiveData
that are provided by Libraries, I would not assume it is non-null unless the library documentation mentioned it.