Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Event Bus

Using first version of RxJava and RxAndroid I had following class as EventBus:

public class RxBus {
private static RxBus instance;
private PublishSubject<Object> subject = PublishSubject.create();

public static RxBus instanceOf() {
    if (instance == null) {
        instance = new RxBus();
    }
    return instance;
}

public void setMessage(Object object) {
    subject.onNext(object);
}

public Observable<Object> getEvents() {
    return subject;
}
}

Getting instance via instanceOf in any class I used setMessage method to emit messages and following code to get emitted messages:

  bus.getEvents().subscribe(new Action1<Object>() {
        @Override
        public void call(Object o) {
            if (o instanceof String) {
                //TODO
            }
        }
    });

Action1 was from rx.functions package. Trying to migrate use RxJava 2 I cannot import it.

Tell me please, what is the shortest way to use RxJava 2 as EventBus

like image 902
Igor Skryl Avatar asked May 03 '17 13:05

Igor Skryl


People also ask

What is an event bus?

An event bus is a pipeline that receives events. Rules associated with the event bus evaluate events as they arrive. Each rule checks whether an event matches the rule's criteria. You associate a rule with a specific event bus, so the rule only applies to events received by that event bus.

What is RxBus in Android?

RxBus - An event bus by ReactiveX/RxJava/ReactiveX/RxAndroid. This is an event bus designed to allowing your application to communicate efficiently.


1 Answers

In RxJava2, the Action1 has been renamed to Consumer.

The remaining action interfaces were named according to the Java 8 functional types. The no argument Action0 is replaced by the io.reactivex.functions.Action for the operators and java.lang.Runnable for the Scheduler methods. Action1 has been renamed to Consumer and Action2 is called BiConsumer. ActionN is replaced by the Consumer<Object[]> type declaration.

See What's different in 2.0

like image 106
Lamorak Avatar answered Oct 09 '22 17:10

Lamorak