LiveData 阻止在开始观察时接收最后一个值

2023-12-13

是否可以预防LiveData开始观察时收到最后一个值? 我正在考虑使用LiveData作为事件。

例如,显示消息、导航事件或对话框触发器等事件,类似于EventBus.

与之间的通信相关的问题ViewModel和片段,谷歌给了我们LiveData用数据更新视图,但是当我们只需要使用单个事件更新视图一次时,这种类型的通信不适合,而且我们无法在中保存视图的引用ViewModel并调用一些方法,因为它会造成内存泄漏。

我发现了类似的东西单一现场活动- 但它仅适用于 1 个观察者,不适用于多个观察者。

- - 更新 - -

正如@EpicPandaForce 所说“没有理由不使用 LiveData“,问题的意图可能是MVVM 中视图和 ViewModel 之间通过 LiveData 进行通信


我在 MutableLiveData 中使用来自 Google Samples 的 EventWraper 类

/**
 * Used as a wrapper for data that is exposed via a LiveData that represents an event.
 */
public class Event<T> {

    private T mContent;

    private boolean hasBeenHandled = false;


    public Event( T content) {
        if (content == null) {
            throw new IllegalArgumentException("null values in Event are not allowed.");
        }
        mContent = content;
    }
    
    @Nullable
    public T getContentIfNotHandled() {
        if (hasBeenHandled) {
            return null;
        } else {
            hasBeenHandled = true;
            return mContent;
        }
    }
    
    public boolean hasBeenHandled() {
        return hasBeenHandled;
    }
}

在视图模型中:

 /** expose Save LiveData Event */
 public void newSaveEvent() {
    saveEvent.setValue(new Event<>(true));
 }

 private final MutableLiveData<Event<Boolean>> saveEvent = new MutableLiveData<>();

 public LiveData<Event<Boolean>> onSaveEvent() {
    return saveEvent;
 }

在活动/片段中

mViewModel
    .onSaveEvent()
    .observe(
        getViewLifecycleOwner(),
        booleanEvent -> {
          if (booleanEvent != null)
            final Boolean shouldSave = booleanEvent.getContentIfNotHandled();
            if (shouldSave != null && shouldSave) saveData();
          }
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LiveData 阻止在开始观察时接收最后一个值 的相关文章