Why is the value param nullable in Observer from A

2019-06-17 05:47发布

问题:

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?

回答1:

Fixed in androix.lifecycle 2.0.0-beta01.

Please report android Team if you encounter any issues.



回答2:

  1. I think the fact that they made it Nullable is that they wanted to add the functionality for those who want to reset the liveData by nulling it's value. Also someone might want a nullable LiveData (and use that null in observe).

  2. If you are creating/producing the LiveData, you could assume it is null (and use the !! operator) since a null would indicate an unexpected error. Also you could create a class like NonNullLiveData that ignores the values that are null in it's setValue. That way you could be sure that you never recieve nulls in your observe (although you can't make the @Nullable go away from the observer).



回答3:

Starting from 2.0.0-beta01 and later androidx.lifecycle version the onChangedparameter 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.