Frage

I want to use RxJava like I would used Guava's EventBus or Otto, but I don't see how I can get it to function that way.

This is the scenario: let's say I want to have a button in my Android app and every time a button is pressed I want RxJava to emit an event via my Observable. It seems to me that I have to have the service reregister after it gets an event and that the activity would need to create a new observable as well.

Like if I say

Observable.from(x)

seems to me I would need to that for every event, but that creates a new observable that would need to be registered to again. Surely I am missing something.

War es hilfreich?

Lösung

You may want to 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 could inject the Subject interface into the Service and the PublishSubject into the Activity (or vice versa depending on what your doing) you can have a good separation of concerns.

Andere Tipps

The newly added refCount operator for ConnectableObservable being added in 0.14.3 will also be useful to you for this type of use case.

It supports automatic connect/disconnect as multiple observers come and go.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top