reactive-streams-commons icon indicating copy to clipboard operation
reactive-streams-commons copied to clipboard

Reactive puzzlers (working title)

Open akarnokd opened this issue 8 years ago • 2 comments

This issue, similar to #21, collects some interesting cases and pitfalls in the form of Java Puzzlers, giving a scenario and offering 4-6 answers.

akarnokd avatar May 02 '16 17:05 akarnokd

  1. What happens if you run the following code?
Observable.empty().repeat().subscribe();

[ ] Nothing, completes normally [ ] Throws MissingBackpressureException [ ] Throws OnErrorNotImplementedException [X] Goes into an infinite loop

The operator repeat resubscribes to the source when it completes. In this case, the empty() completes immediately, gets resubscribed and completes immediately again, ad infinitum.

Note that the same thing can happen with terminated subjects such as PublishSubject and BehaviorSubject or an empty ReplaySubject!

Takeaway: never repeat a source indefinitely, especially from an unknown source.

akarnokd avatar May 02 '16 17:05 akarnokd

  1. What happens when you run the following code?
PublishSubject<Integer> ps = PublishSubject.create();

ps.subscribeOn(Schedulers.computation()).subscribe(v -> System.out.println(Thread.currentThread.getName()));

Thread.sleep(1000);

ps.onNext(1);

[X] Prints main [ ] Prints 1 [ ] Prints RxComputationScheduler-1 [ ] Throws an Exception

The operator subscribeOn has no effect on a running PublishSubject because it doesn't have any visible subscription side-effects. However the other subjects may signal a value or completion on the given Scheduler.

akarnokd avatar May 02 '16 18:05 akarnokd