Reputation: 16914
Say I have a generic 'Button' in any kind of modern UI framework (I'm working with Android's right now but the problem is pretty much plaform-agnostic). I can put a listener onto this button to listen for click events. My listener gets notified about click events on the UI-thread. This is a problem from a reactive-point-of-view, more specifically in the context of threading.
I can easily create a Subject for the click events. The Observer would most likely want to do processing on another thread. But I can't easily extract (without hacking or ugly workarounds) the Scheduler's Worker from an .observeOn()
operator, for dispatching the event onto the correct Worker.
How do I create an Observable stream from these click events, so that the stream will respect the Scheduling requirements of the .observeOn()
operator?
Upvotes: 1
Views: 420
Reputation: 69997
It's not clear to me what exactly the issue is here. ObserveOn puts the events to the specified scheduler, which behind the scenes may end up on different threads for different subscribers. If you want to make sure every subscriber will receive the events exactly on the same thread, you need to have a Scheduler with exactly one backing thread. The easiest way of getting such Scheduler is by wrapping an ExecutorService:
Scheduler s = Schedulers.from(Executors.newSingleThreadedExecutor());
PublishSubject<Event> ps = PublishSubject.create();
Observable<Event> events = ps.observeOn(s);
events.subscribe(...);
events.subscribe(...);
ps.onNext(...);
Upvotes: 1