RxJava and random sporadic events on Android

I want to use RxJava as if I were using Guava EventBus or Otto, but I don’t see how I can make it function that way.

This is a scenario: let's say I want to have a button in my Android app, and every time the button is clicked, I want RxJava to emit an event through my Observable. It seems to me that I should have the reregister service after it receives the event, and that for this action it will also be necessary to create a new observable.

As if i said

 Observable.from(x) 

It seems to me that I need this for each event, but this creates a new observable that will need to be registered again. Of course, I'm missing something.

+7
java android rx-java
source share
2 answers

You can do something like this (from rx.subjects.PublishSubject):

 PublishSubject<Object> subject = PublishSubject.create(); // observer1 will receive all onNext and onCompleted events subject.subscribe(observer1); subject.onNext("one"); subject.onNext("two"); // observer2 will only receive "three" and onCompleted subject.subscribe(observer2); subject.onNext("three"); subject.onCompleted(); 

If you can introduce the Subject interface into a service and PublishSubject into an Activity (or vice versa depending on what you are doing), you can have a good separation of problems.

+6
source share

The recently added refCount statement for ConnectableObservable, added in 0.14.3 , will also be useful to you for this type of use.

It supports automatic connection / disconnection when several observers come and go.

+3
source share

All Articles