Reputation: 11408
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
Upvotes: 12
Views: 5718
Reputation: 3576
A little late answer but a slightly better option for your scenarion than the BehaviorSubject could be BehaviorRelay from RxRelay lib. and also for more global solutions when you need different behaviors but want to share single point of interaction between all modules you can use RxHub
Upvotes: 5
Reputation: 6594
I think it is more simple if you use BehaviorSubject with switchOnNext operator.
switchOnNext( ) convert an Observable that emits Observables (BehaviorSubject in this example) into a single Observable that emits the items emitted by the most-recently emitted of those Observables
the Observable returned by switchOnNext( ) unsubscribes from the previously-emitted Observable begins emitting items from the latest Observable
public class PhotoModel{
BehaviorSubject<Observable<Photo>> subject = BehaviorSubject.create(...);
public void setUserId(String id){
subject.onNext(Api.getUserPhoto(photoId));
}
public Observable<Photo> subscribeToPhoto(){
return Observable.switchOnNext(subject);
}
}
When should one use RxJava Observable and when simple Callback on Android?
Upvotes: 3
Reputation: 26251
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.
Upvotes: 8