19

有没有办法强制 LiveData 值不可为空?默认观察者实现似乎有 @Nullable 注释,它强制 IDE 建议该值可能为 null 并应手动检查:

public interface Observer<T> {
    /**
     * Called when the data is changed.
     * @param t  The new data
     */
    void onChanged(@Nullable T t);
}
4

6 回答 6

6

如果您使用 Kotlin,您可以使用扩展创建更好的非空观察函数。有一篇关于它的文章。https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333

于 2018-04-20T12:25:01.477 回答
5

只有当您控制设置数据的代码时才能安全地执行此操作,因为您还必须包装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安全。

于 2018-05-03T12:13:59.683 回答
5

如果您使用Kotlin. 您可以替换LiveDataStateFlow。它更适合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之前是实验性的。

这里有一些关于替换LiveDataStateFlow.

正如Igor Bubelov指出的那样,这种方法的另一个优点是它不是Android特定的,因此可以在多平台项目的共享代码中使用。

于 2020-10-25T06:50:24.857 回答
4

虽然您可以做一些事情,但您有责任确保您不会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);
}
于 2017-10-22T15:45:27.157 回答
3
fun <T> LiveData<T>.observeNonNull(owner: LifecycleOwner, observer: (t: T) -> Unit) {
    this.observe(owner, Observer {
        it?.let(observer)
    })
}
于 2019-11-20T22:32:49.970 回答
0

您必须做一些额外的工作来处理来自库本身的空值。

例如,当您LiveData@DaoRoom 中返回 a 时,例如:

@Dao interface UserDao {

    @get:Query("SELECT * FROM users LIMIT 1")
    val user: LiveData<User>

}

并观察实时数据,如果没有用户user,它将调用onChanged带有值的回调。null

于 2018-01-13T20:17:33.790 回答