Reputation: 4338
I'm looking at examples and reading documentation and I've found some problems while trying to subscribe on Flux in a parallel manner.
I have a 3 functions, as below.
private val log = LoggerFactory.getLogger("main")
private val sequence = Flux.just(1, 2)
fun a() {
sequence.subscribeOn(Schedulers.parallel()).subscribe { log.info("*** {}", it) }
sequence.subscribe { log.info(">>> {}", it) }
}
fun b() {
sequence.subscribe { log.info(">>> {}", it) }
}
fun c() {
sequence.subscribeOn(Schedulers.parallel()).subscribe { log.info("*** {}", it) }
}
Now, when I run each method separately I have a proper output from functions a()
and b()
, but output from c()
is empty. Is that to be expected, is it by design? If so, why is that happening?
Upvotes: 1
Views: 1274
Reputation: 28301
Flux.just(...)
captures value(s) and thus is optimized to execute immediately in the subscribing Thread
.
When you use subscribeOn
, you change that subscribing Thread
from main
to something else, making the just
truly asynchronous.
In a()
, without a subscribeOn
that second just
would block the main thread just enough that the test doesn't finish before the asynchronous alternative completes.
In c()
, there is no such blocking of the main
thread. As a consequence, the test terminates before the asynchronous just
has had time to emit anything, and that is why you see no output.
To make that more visible, add a Thread.sleep(10)
and you'll see some output.
Upvotes: 5