Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing EventBus with RxJava - N subscribers always listening

I am replacing an EventBus pattern with RxJava in an Android app. I had events to alert any interested parties of updates to data in my cache singleton. Any time a web service was called, the data would be updated, and the subscribers would be alerted via a posted event.

I have something close to this set up in RxJava with AsyncSubject. The observers get a single event from the subject, but then they get an onComplete event and unsubscribe. This works as the UI first loads, but when the data needs to be refreshed, there are no subscribers to be notified. How do I tell those Subscribers to keep listening for more onNext events from the Subject?

I need a Subject that will report the most recent item. PublishSubject only emits items after subscription, so it doesn't quite meet my needs. My subscribers start observing at different times (possibly after the first data event), so I need the Subject to emit the last item observed and then keep the stream open for subsequent items. It seems like a combination of AsyncSubject and PublishSubject is what I need. Is there some way to accomplish this with the built in classes, or do I need to create my own subject?

WebServiceObservable OR CacheObservable
                  ^
                  |
             AsyncSubject
                  ^
                  |
                /   \
              /       \
            /           \
      UiObserver1   UiObserver2
like image 808
Austyn Mahoney Avatar asked Jul 23 '14 18:07

Austyn Mahoney


1 Answers

BehaviorSubject will fit your needs. https://github.com/Netflix/RxJava/wiki/Subject#behaviorsubject

If you need more sophisticated behavior you can always write your own Subject implementation. It seems pretty straightforward to do so.

like image 131
tomrozb Avatar answered Nov 15 '22 23:11

tomrozb