RxAndroid事件总线,避免从适配器发送重复的事件 [英] RxAndroid Event Bus and avoid duplicated events sent from an Adapter

查看:281
本文介绍了RxAndroid事件总线,避免从适配器发送重复的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基于RxJava和本文实现了一个简单的事件总线:解决方案

如果可以确定两个后续事件相同还是不同,则可以使用distinctUntilChanged(Func1),否则,可以尝试使用debounce()毫秒. >

I implemented a simple event bus based on RxJava and this article: http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/

Everything works fine except I have to listen / fire events from an adapter class, which is initialized by a fragment multiple times. Because I am subscribed to each instance of that adapter, my events are being fired multiple times resulting in errors.

I would like to get subscribed to only 1 instance of that adapter and it has to be last one (not the first one). So is there a way, that in case a new instance of the adapter is spawned, I can somehow detect if I already have been subscribed and update the subscription (or delete all previous ones of that adapter and just subscribe to the current one)? Please note I also use the rxBus singleton in my other fragments / services, so I cannot just simply reset it entirely as then I will loose all other subscriptions not coming from the adapter.

Here is my code of the bus:

public class APIRxBus {
private static APIRxBus instance = null;
private final Subject<Object, Object> bus = new SerializedSubject<>(BehaviorSubject.create());

public static APIRxBus getInstance() {
    if (instance == null){
        instance = new APIRxBus();
    }
    return instance;
}

public void send(Object o) {
    bus.onNext(o);
}

public Observable<Object> toObserverable() {
    return bus;
}

}

and here of my subscription in the adapter class:

rxBus = APIRxBus.getInstance();

    rxBus.toObserverable()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
        @Override
        public void call(Object event) {

            if (event instanceof EVTSetPrintMode) {
                //...
            } else if (event instanceof EVTChangeDocumentImportance) {

                //...

            } else if (event instanceof EVTChangeDocumentVisibility) {
                //...
            }
        }
    });

解决方案

You could use distinctUntilChanged(Func1) if you can tell two subsequent events are the same or not, otherwise, you could try debounce() with some milliseconds.

这篇关于RxAndroid事件总线,避免从适配器发送重复的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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