RxJava as an event bus in an Android project - remove an event from the bus

I used to work with EventBus, which was easy to use and understandable. This time, however, I would like to try RxJava for messaging with the event bus, however it’s not entirely clear how to remove events from RxJava or, rather, how to design it correctly to have a similar behavior like EventBus when I call removeStickyEvent?

In RxJava, I can use BehaviorSubject to respond last, even when I subscribe to this observable, but what should I do when this event is processed? What if I do not want to repeat this event again?

For example, a single fragment fires an event and then ends. Another fragment listens to this event and processes it. Then, if this application activates this “other” activity again from different circumstances, it will again be subscribed to the same BehaviorSubject and process this obsolete event again, which I would not want to achieve.

I used this project as a link https://github.com/marwinxxii/AndroidRxSamples/blob/master/app/src/main/java/com/github/marwinxxii/rxsamples/EventBusSampleActivity.java

+4
source share
1 answer

Until you plan to use it events null, I think this can be achieved quite easily.

, BehaviorSubject sticky, removeStickyEvent bus, null ( "" subject).

- ( - , , Object -event):

public class RxEventBus {

    PublishSubject<Object> eventsSubject = PublishSubject.create();
    BehaviorSubject<Object> stickyEventsSubject = BehaviorSubject.create();

    public RxEventBus() {
    }

    public Observable<Object> asObservable() {
        return eventsSubject;
    }

    public Observable<Object> asStickyObservable() {
        return stickyEventsSubject.filter(new Func1<Object, Boolean>() {
            @Override
            public Boolean call(Object o) {
                return o != null;
            }
        });
    }

    public void postEvent(@NonNull Object event) {
        eventsSubject.onNext(event);
    }

    public void postStickyEvent(@NonNull Object stickyEvent) {
        stickyEventsSubject.onNext(stickyEvent);
    }

    public void removeStickyEvent(){
        stickyEventsSubject.onNext(null);
    }
}
+6

All Articles