为什么在Android Architecture Components的Observer中,值param可以为空? [英] Why is the value param nullable in Observer from Android Architecture Components?
问题描述
来自架构组件的LiveData定义了一个具有可为空的值的Observer,用于接收者回调:
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);
}
为什么有显式可为空的注释?
LiveData.observe()
的文档还显示:
如果LiveData已经设置了数据,它将被发送给观察者.
If LiveData already has data set, it will be delivered to the observer.
例如观察者会等待不可为空的更新,或立即收到以前的不可为空的值,该值在Kotlin中尤其如此,直到我将T
定义为可为空.
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.
代码似乎可以这样工作.我了解为什么LiveData.getValue()
不能满足要求,在发送第一个数据之前可以手动调用LiveData.getValue()
(并因此检查mData != NOT_SET
返回空值).
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).
第二个问题是:当T为不可为空时,可以安全地假设Kotlin中的值为非为空吗?
推荐答案
已修复 androix.lifecycle 2.0.0-beta01
.
如果遇到任何问题,请报告 Android团队.
Please report android Team if you encounter any issues.
这篇关于为什么在Android Architecture Components的Observer中,值param可以为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!