Sobes.tech
Senior

What is the difference between publishOn and subscribeOn in Reactor?

sobes.tech AI

Answer from AI

In Reactor, subscribeOn and publishOn control threads but do so in different ways:

  • subscribeOn — sets the Scheduler on which the subscription and all upstream (data source) execution will occur. It affects the thread where data generation begins.

  • publishOn — switches the execution thread for downstream (after the call to publishOn). That is, after calling publishOn, all operators will execute on the specified Scheduler.

Example:

Flux.range(1, 5)
    .map(i -> {
        System.out.println("Map 1: " + Thread.currentThread().getName());
        return i;
    })
    .publishOn(Schedulers.boundedElastic())
    .map(i -> {
        System.out.println("Map 2: " + Thread.currentThread().getName());
        return i;
    })
    .subscribeOn(Schedulers.parallel())
    .subscribe(i -> System.out.println("Received: " + i + " on " + Thread.currentThread().getName()));

Here, subscription and upstream will run on Schedulers.parallel(), and after publishOn, the thread switches to Schedulers.boundedElastic().

Summary:

  • subscribeOn affects the thread of subscription and data generation.
  • publishOn switches the execution thread for subsequent operators.

This is important for managing asynchrony and optimizing performance in reactive chains.