in RxJava what counts as an Asynchronous Boundary?

Viewed 113

I'm currently doing a deep dive into the dangers of Java threading and specifically how these apply to RxJava. Answers are appreciated, but to forestall the inevitable RTFM I'd also appreciate references to said manual.

I've heard the term Asynchronous Boundary thrown around a lot and I have a general idea but I haven't found a strict definition.

Where are the Asynchronous Boundaries in these examples?

// example 1
Observable.just(123)
         .map(i -> i + 1)
         .subscribe(System.out::println); 

// example 2
Observable.just(123)
         .observeOn(Schedulers.newThread())
         .map(i -> i + 1)
         .subscribe(System.out::println); 

// example 3
Observable.just(123)
          .subscribeOn(Schedulers.newThread())
          .map(i -> i + 1)
          .subscribe(System.out::println);

Are there any other examples that are relevant.

1 Answers

An operator is an asynchronous boundary if 1) it uses time, 2) takes an asynchronous Scheduler and/or 3) is involved with more than one reactive source.

For 1), this could mean that the downstream could receive signals on the original thread or the standard default Scheduler. Example: timeout.

For 2), an operator takes an asynchronous Scheduler and routes events and/or control signals through that scheduler. The standard schedulers, except trampoline, are asynchronous schedulers. Example: observeOn, subscribeOn, unsubscribeOn.

For 3), multiple sources are involved of which each could emit from its own thread. The outcome and downstream then could be notified on any of these threads (or even the thread triggering the initial subscription) and often all bets are off what thread it is going to be. Example: merge, flatMap.

Beyond these, if Flowable is involved, backpressuring inside operators can act as an asynchronous boundary as emission from an upstream thread must be coordinated with request from a downstream/arbitrary thread. In this case, any of the participating thread can be responsible for signal emission and it can change dynamically. Example: onBackpressureBuffer, observeOn, create

Related