Sobes.tech
Senior

How to subscribe to Flux/Mono in reactive programming? What options are available?

sobes.tech AI

Answer from AI

In reactive programming in Java using Project Reactor for subscribing to Flux or Mono, there are several options:

  1. The subscribe() method — the basic way to subscribe and handle elements, errors, and completion:
flux.subscribe(
    value -> System.out.println("Received: " + value),
    error -> System.err.println("Error: " + error),
    () -> System.out.println("Completed")
);
  1. Using Consumer to handle only values:
mono.subscribe(value -> System.out.println("Result: " + value));
  1. Subscription with Disposable:
Disposable disposable = flux.subscribe();
// You can cancel the subscription later
disposable.dispose();
  1. Subscription using doOnNext, doOnError, doOnComplete for side effects:
flux
  .doOnNext(value -> System.out.println("Received: " + value))
  .doOnError(error -> System.err.println("Error: " + error))
  .doOnComplete(() -> System.out.println("Completed"))
  .subscribe();
  1. Subscription with a Subscriber:

You can implement the Subscriber interface for more fine-grained control over the subscription, such as managing backpressure.

flux.subscribe(new BaseSubscriber<>() {
    @Override
    protected void hookOnNext(T value) {
        System.out.println("Received: " + value);
        request(1); // Request the next element
    }
});

Thus, the choice of subscription method depends on your needs: simple processing, managing the subscription lifecycle, or controlling the data flow.

How to subscribe to Flux/Mono in reactive… - sobes.tech