spring-attic / reactive-streams-commons

A joint research effort for building highly optimized Reactive-Streams compliant operators.
Apache License 2.0
357 stars 51 forks source link

Reactive puzzlers (working title) #22

Open akarnokd opened 8 years ago

akarnokd commented 8 years ago

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 commented 8 years ago

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 commented 8 years ago

2) 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.