gpt4 book ai didi

android - LiveData 防止在开始观察时收到最后一个值

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:14 24 4
gpt4 key购买 nike

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

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

关于 ViewModel 和 fragment 之间通信的问题,Google 给了我们 LiveData 来用数据更新 View ,但是当我们需要更新时这种通信方式不适合View only once with single event,我们也不能在 ViewModel 中保存 View 的引用并调用一些方法,因为它会造成内存泄漏。

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

---更新----

正如@EpicPandaForce 所说“没有理由将 LiveData 用作它不是的东西”,问题的 Intent 可能是 Communication between view and ViewModel in MVVM with 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;
}
}

在 View 模型中:

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

在 Activity/fragment 中

mViewModel
.onSaveEvent()
.observe(
getViewLifecycleOwner(),
booleanEvent -> {
if (booleanEvent != null)
final Boolean shouldSave = booleanEvent.getContentIfNotHandled();
if (shouldSave != null && shouldSave) saveData();
}
});

关于android - LiveData 防止在开始观察时收到最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49832787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com