2

What is the equivalent of getStickyEvent() from EventBus in RxJava.

I would like to subscribe to observables from "screens" that are not in the foreground/not active, but at anytime very well may pop in.

If events are continuously happening, I want these "screens" to receive them the next time they are active/in the foreground.

Edit:

It sounds like I should have a replaySubject, and then when the "Screen" comes to the foreground subcribe to it.....?

  BehaviorSubject – emits the last emitted item when subscribed to,
  then continues to emit items from the source observable
sirvon
  • 2,547
  • 1
  • 31
  • 55
  • I'll reference this, for anyone else because it helped me....http://stackoverflow.com/questions/25457737/how-to-create-an-observable-from-onclick-event-android – sirvon Sep 25 '14 at 00:04

1 Answers1

2

You already gave the answer yourself but just to confirm: Yes, you would use either BehaviorSubject or ReplaySubject.

After a new subscriber subscribes, they will both emit to that subscriber all items they receive from then onwards. However, each has a little extra beyond that:

  • BehaviorSubject will always start that sequence by immediately emitting the (one) most recent of the items it has received before the subscriber subscribed, if there was any. If there was none it will emit a default item if one was provided when it was created.
  • ReplaySubject will always start that sequence by immediately emitting (some or) all of the items it has recevied since its creation in the order that it received it. ReplaySubject can be initialized to limit the number of items it keeps in the cache for later subsribers, or to limit the amount of time that it will keep items in the cache. But (as far as I know), you cannot provide a default value if using a ReplaySubject.

Then, calling

subject.subscribe(new Subscriber<YourEventClass>() {
    // implement Subscriber methods here
});

would be more or less equivalent to:

eventbus.registerSticky(this);

and having this implement the callbacks for the EventBus.

Synchronous vs Asynchronous

Note, though, that subscribing like this still makes the delivery of items from the subject asynchronous (like register/registerSticky), as you are in both cases only handing over some callback methods and are not waiting right there for the result to be returned.

I have not used the greenrobot EventBus myself but it seems that getStickyEvent() is synchronous/blocking.

If you want blocking behavior you would have to - instead of subscribing to it - convert the subject to a blocking observable (with subject.toBlocking()).

See here for more on blocking observables:

https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators

but basically you can then transform them to an iterable, or just get the latest item, or a number of other things.

david.mihola
  • 12,062
  • 8
  • 49
  • 73