本文介绍了LiveData 防止在开始观察时接收最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Is it possible to prevent LiveData receive the last value when start observing?I am considering to use LiveData as events.

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

For example events like show message, a navigation event or a dialog trigger, similar to EventBus.

ViewModel 和fragment 之间的通信问题,Google 给了我们LiveData 来更新view 的数据,但是这种类型的通信不适合我们需要更新的时候单个事件只查看一次,我们也不能在 ViewModel 中保存视图的引用并调用一些方法,因为它会造成内存泄漏.

The problem related to communication between ViewModel and fragment, Google gave us LiveData to update the view with data, but this type of communication not suitable when we need update the view only once with single event, also we cannot hold view's reference in ViewModel and call some methods because it will create memory leak.

我发现了类似的东西 SingleLiveEvent - 但它只适用于 1 个观察者,而不适用于多个观察者.

I found something similar SingleLiveEvent - but it work only for 1 observer and not for multiple observers.

--- 更新----

正如@EpicPandaForce 所说的没有理由将 LiveData 用作它不是的东西",问题的意图可能是 MVVM 中视图和 ViewModel 之间的通信与 LiveData

As @EpicPandaForce said "There is no reason to use LiveData as something that it is not", probably the intent of the question was Communication between view and ViewModel in MVVM with LiveData

推荐答案

我在 MutableLiveData 中使用 Google Samples 中的这个 EventWraper 类

I`m using this EventWraper class from Google Samples inside MutableLiveData

/**
 * 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();
          }
        });

这篇关于LiveData 防止在开始观察时接收最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:42