事件包装器模式是否取代了 SingleLiveEvent 的使用?

Does event wrapper pattern replace the use of SingleLiveEvent?

我最近在我的 Android 应用中采用 MVVM。为了解决应用生命周期的底层问题,Google发布了LiveData。

LiveData的使用有不同的场景,正如medium article wrote by Jose Alcérreca中所指出的,您可以使用SingleLiveEvent或类似事件包装器模式的东西。

我想确保今年(2018)的SingleLiveEvent, or the event wrapper pattern, which one would be the best practice to use with LiveData in Android MVVM architecture. And I found the Google I/O app没有使用SingleLiveEvent,它使用事件包装模式 代替。

之前开过一个issue on the project android-architecture,一开始是求官方回复,但是貌似没什么意见。因此,我想听听已经使用这些东西并对此有反思的开发人员的建议。

请分享您的宝贵经验,先谢谢了。

我不喜欢 SingleLiveEvent,因为它仅限于一个观察者,但您也可以添加许多观察者,因此它很容易出错。

但在非常简单的场景中(比如您提到的待办事项应用),它可能是比事件包装器模式更好的选择。

在复杂的场景下,事件包装器模式会是更好的选择,但它也有一些局限性。 This implementation 假设您只有一个 main 消费者(参见 getContentIfNotHandled)。所以,我认为与多个观察者打交道会导致样板决定哪个是主要消费者,或者我应该何时调用 getContentIfNotHandledpeekContent

但是,所有这些限制都可以通过您自己的实现来解决。

例如这里有一个 SingleLiveEventextended version 支持多个观察者:

public class SingleLiveEvent<T> extends MutableLiveData<T> {
private LiveData<T> liveDataToObserve;
private final AtomicBoolean mPending = new AtomicBoolean(false);

public SingleLiveEvent() {
    final MediatorLiveData<T> outputLiveData = new MediatorLiveData<>();
    outputLiveData.addSource(this, currentValue -> {
        outputLiveData.setValue(currentValue);
        mPending.set(false);
    });
    liveDataToObserve = outputLiveData;
}

    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        liveDataToObserve.observe(owner, t -> {
            if(mPending.get()) {
                observer.onChanged(t);
            }
        });
    }

    @MainThread
    public void setValue(T value) {
        mPending.set(true);
        super.setValue(value);
    }
}

如您所见,这与 SingleLiveEvent vs 事件包装器模式无关,这完全取决于。就个人而言,我使用其他模式(如 React/Flux 世界中存在的模式)来处理状态。

请记住,软件工程中没有灵丹妙药。

SingleLiveData仅限一个观察者,this文章中描述的EventLiveData支持多个观察者。

您可以像使用常规实时数据一样使用它。不会对代码进行黑客攻击或增加不必要的复杂性。

implementation 'com.rugovit.eventlivedata:eventlivedata:1.0'

MutableEventLiveData<String>  eventLiveData =new MutableEventLiveData<>(); 
viewModel.event.observe(this, Observer {
    // ...
})
 

它是livedata的扩展,支持livedata的所有特性。 与其他解决方案不同,此 支持多个观察者

Github link: https://github.com/rugovit/EventLiveData