LiveData防止在开始观察时接收到最后一个值 [英] LiveData prevent receive the last value when start observing

本文介绍了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 和片段之间的通信有关的问题,Google向我们提供了 LiveData 来用数据更新视图,但是这种类型的通信不适用于我们需要更新仅在单个事件中查看一次,我们也无法在 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.

我发现了类似的内容

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

---更新----

@EpicPandaForce说"没有理由将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;
    }
}

在ViewModel中:

 /** 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防止在开始观察时接收到最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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