问题描述
我更愿意在可能的地方不使用可空引用。对我来说,这很容易出错。是的,我知道在某些特殊情况下有意义,但这些情况很小。
我喜欢Android LiveData
反应模式。
但是LiveData
和mutablelivedata
允许包含NULL引用。这与我在编程方面的一般偏好相冲突(请参见上面的第一行)。
也许在Google中,他们不了解或不同意NULL Object Pattern。
旁注:我在Kotlin(using class extension)中找到了一篇不错的文章:如何做到这一点:但是Kotlin对我来说不是一个案例,我被Java锁定了。
因此,我尝试创建自己的两个类的后代:
public class NonNullLiveData<T> extends LiveData<T> {
public NonNullLiveData(@NonNull final T value) {
super(Objects.requireNonNull(value));
}
@NonNull public T getValue() {
return Objects.requireNonNull(super.getValue());
}
}
并且:
public class NonNullmutablelivedata<T> extends NonNullLiveData<T> {
public NonNullmutablelivedata(@NonNull final T value) {
super(value);
}
@Override public void setValue(@NonNull final T value) {
super.setValue(Objects.requireNonNull(value));
}
@Override public void postValue(@NonNull final T value) {
super.postValue(Objects.requireNonNull(value));
}
}
我使用了一段时间,感到非常高兴:不再需要额外的IF和断言。
直到进行双向绑定:
android:text="@={vmo.editable}"
(当然,可编辑的类型为NonNullmutablelivedata<String>
。)
[databinding] {"msg":"The expression "vmoEditable.getValue()" cannot be inverted,so it cannot be used in a two-way binding
Details: There is no inverse for method getValue,you must add an @InverseMethod
annotation to the method to indicate which method should be used when
using it in two-way binding expressions
我在上面的@InverseMethod
建议周围做了很多尝试,但没有任何帮助(我觉得@InverseMethod
并非用于此目的,而构建错误的建议实际上是误导)。
有什么办法使它起作用吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)