有没有办法强制 LiveData 值不可为空?默认观察者实现似乎有 @Nullable 注释,它强制 IDE 建议该值可能为 null 并应手动检查:
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(@Nullable T t);
}
有没有办法强制 LiveData 值不可为空?默认观察者实现似乎有 @Nullable 注释,它强制 IDE 建议该值可能为 null 并应手动检查:
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(@Nullable T t);
}
如果您使用 Kotlin,您可以使用扩展创建更好的非空观察函数。有一篇关于它的文章。https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333
只有当您控制设置数据的代码时才能安全地执行此操作,因为您还必须包装LiveData
类。这样,数据设置方法将受到保护,@NonNull
您可以确保在到达Observer
.
包装LiveData
类:
public class NonNullMutableLiveData<T> extends MutableLiveData<T> implements NonNullLiveData<T> {
private final @NonNull T initialValue;
public NonNullMutableLiveData(@NonNull T initialValue) {
this.initialValue = initialValue;
}
@Override
public void postValue(@NonNull T value) {
super.postValue(value);
}
@Override
public void setValue(@NonNull T value) {
super.setValue(value);
}
@NonNull
@Override
public T getValue() {
//the only way value can be null is if the value hasn't been set yet.
//for the other cases the set and post methods perform nullability checks.
T value = super.getValue();
return value != null ? value : initialValue;
}
//convenience method
//call this method if T is a collection and you modify it's content
public void notifyContentChanged() {
postValue(getValue());
}
public void observe(@NonNull LifecycleOwner owner, @NonNull NonNullObserver<T> observer) {
super.observe(owner, observer.getObserver());
}
}
创建一个暴露为不可变的接口:
public interface NonNullLiveData<T> {
@NonNull T getValue();
void observe(@NonNull LifecycleOwner owner, @NonNull NonNullObserver<T> observer);
}
最后,包装Observer
:
//not implementing Observer<T> to make sure this class isn't passed to
//any class other than NonNullMutableLiveData.
public abstract class NonNullObserver<T> {
public Observer<T> getObserver() {
return new ActualObserver();
}
public abstract void onValueChanged(@NonNull T t);
private class ActualObserver implements Observer<T> {
@Override
public void onChanged(@Nullable T t) {
//only called through NonNullMutableLiveData so nullability check has already been performed.
//noinspection ConstantConditions
onValueChanged(t);
}
}
}
现在您可以像这样创建数据:
class DataSource {
private NonNullMutableLiveData<Integer> data = new NonNullMutableLiveData<>(0);
public NonNullLiveData<Integer> getData() {
return data;
}
}
并像这样使用它:
dataSource.getData().observe(this, new NonNullObserver<Integer>() {
@Override
public void onValueChanged(@NonNull Integer integer) {
}
});
完全null
安全。
如果您使用Kotlin
. 您可以替换LiveData
为StateFlow。它更适合Kotlin
代码并提供内置的 null 安全性。
而不是使用:
class MyViewModel {
val data: LiveData<String> = MutableLiveData(null) // the compiler will allow null here!
}
class MyFragment: Fragment() {
model.data.observe(viewLifecycleOwner) {
// ...
}
}
您可以使用:
class MyViewModel {
val data: StateFlow<String> = MutableStateFlow(null) // compilation error!
}
class MyFragment: Fragment() {
lifecycleScope.launch {
model.data.collect {
// ...
}
}
}
StateFlow
是协程的一部分,要使用lifecycleScope
你需要添加lifecycle-extensions
依赖项:
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
请注意,此 API 在协程 1.4.0之前是实验性的。
这里有一些关于替换LiveData
为StateFlow
.
正如Igor Bubelov指出的那样,这种方法的另一个优点是它不是Android
特定的,因此可以在多平台项目的共享代码中使用。
虽然您可以做一些事情,但您有责任确保您不会null
通过LiveData
. 除此之外,每个“解决方案”更多的是对警告的抑制,这可能很危险(如果您确实获得了空值,您可能无法处理它,Android Studio 也不会警告您)。
您可以添加assert t != null;
. 断言不会在 Android 上执行,但 Android Studio 可以理解。
class PrintObserver implements Observer<Integer> {
@Override
public void onChanged(@Nullable Integer integer) {
assert integer != null;
Log.d("Example", integer.toString());
}
}
添加注释以抑制警告。
class PrintObserver implements Observer<Integer> {
@Override
@SuppressWarnings("ConstantConditions")
public void onChanged(@Nullable Integer integer) {
Log.d("Example", integer.toString());
}
}
这也适用于我安装的 Android Studio,但它可能不适合您,但您可以尝试@Nullable
从实现中删除注释:
class PrintObserver implements Observer<Integer> {
@Override
public void onChanged(Integer integer) {
Log.d("Example", integer.toString());
}
}
您不太可能在 Android 上使用它,但纯粹从 Java 的角度来看,您可以定义一个新接口并在默认方法中添加一个空检查:
interface NonNullObserver<V> extends Observer<V> {
@Override
default void onChanged(@Nullable V v) {
Objects.requireNonNull(v);
onNonNullChanged(v);
// Alternatively, you could add an if check here.
}
void onNonNullChanged(@NonNull V value);
}
fun <T> LiveData<T>.observeNonNull(owner: LifecycleOwner, observer: (t: T) -> Unit) {
this.observe(owner, Observer {
it?.let(observer)
})
}
您必须做一些额外的工作来处理来自库本身的空值。
例如,当您LiveData
从@Dao
Room 中返回 a 时,例如:
@Dao interface UserDao {
@get:Query("SELECT * FROM users LIMIT 1")
val user: LiveData<User>
}
并观察实时数据,如果没有用户user
,它将调用onChanged
带有值的回调。null