问题
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);
}
回答1:
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
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());
}
}
Remove the annotation
This also works in my installation of Android Studio, but it might not work for you, but you could try to just remove the @Nullable
annotation from the implementation:
class PrintObserver implements Observer<Integer> {
@Override
public void onChanged(Integer integer) {
Log.d("Example", integer.toString());
}
}
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);
}
回答2:
If you use Kotlin, you can create much nicer non-null observe function with extension. There is an article about it. https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333
回答3:
It's possible to do it safely only if you are in control of the code which sets the data because you'll also have to wrap the LiveData
class. This way the data setting methods will be protected with @NonNull
and you can be sure that the data has already been checked before reaching the Observer
.
Wrap the LiveData
class:
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());
}
}
Create an interface for exposing as immutable:
public interface NonNullLiveData<T> {
@NonNull T getValue();
void observe(@NonNull LifecycleOwner owner, @NonNull NonNullObserver<T> observer);
}
Finally, wrap the 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);
}
}
}
Now you can create your data like this:
class DataSource {
private NonNullMutableLiveData<Integer> data = new NonNullMutableLiveData<>(0);
public NonNullLiveData<Integer> getData() {
return data;
}
}
And use it like this:
dataSource.getData().observe(this, new NonNullObserver<Integer>() {
@Override
public void onValueChanged(@NonNull Integer integer) {
}
});
Completely null
safe.
回答4:
You would have to do some additional work to handle null values that come from the library itself.
For example, when you return a LiveData
from a @Dao
in Room, like:
@Dao interface UserDao {
@get:Query("SELECT * FROM users LIMIT 1")
val user: LiveData<User>
}
And observe the user
live data, it will call the onChanged
callback with a null
value if there is no user.
回答5:
fun <T> LiveData<T>.observeNonNull(owner: LifecycleOwner, observer: (t: T) -> Unit) {
this.observe(owner, Observer {
it?.let(observer)
})
}
来源:https://stackoverflow.com/questions/46488442/is-it-possible-to-enforce-non-nullability-of-livedata-values