是否可以强制 LiveData 值不可为空? [英] Is it possible to enforce non-nullability of LiveData values?

查看:39
本文介绍了是否可以强制 LiveData 值不可为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to enforce non-nullability of LiveData values? Default Observer implementation seems to have @Nullable annotation which forces an IDE to suggest that the value might be null and should be checked manually:

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

推荐答案

虽然您可以做一些事情,但您有责任确保不会将 null 传递给 实时数据.除此之外,每个解决方案"更像是对警告的抑制,这可能是危险的(如果您确实得到空值,您可能不会处理它,Android Studio 也不会警告您).

While there a few things you can do, it is your responsibility to make sure you don't pass null to the LiveData. In addition to that, every 'solution' is more a suppression of the warning, which can be dangerous (if you do get a null value, you might not handle it and Android Studio will not warn you).

您可以添加assert t != null;.断言不会在 Android 上执行,但 Android Studio 理解它.

You can add assert t != null;. The assert will not be executed on Android, but Android Studio understands it.

class PrintObserver implements Observer<Integer> {

    @Override
    public void onChanged(@Nullable Integer integer) {
        assert integer != null;
        Log.d("Example", integer.toString());
    }
}

抑制警告

添加注释以抑制警告.

Suppress the warning

Add an annotation to suppress the warning.

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 的角度来看,您可以定义一个新接口并在默认方法中添加空检查:

Default methods

It's unlikely you can use this on Android, but purely from a Java perspective, you could define a new interface and add a null check in a default method:

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);
}

这篇关于是否可以强制 LiveData 值不可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆