Java.Reactive.🎯 Who is the Consumer in Reactive Programming?

🧠 Summary

  • Backpressure = “Slow down! I can’t handle that much data right now!”
  • Prevents overwhelming the consumer.
  • Crucial for building robust, scalable, and memory-safe reactive systems.

In a reactive stream, the consumer is the Observer / Subscriber — the one who:

  • Subscribes to the stream (subscribe(...))
  • Processes each item received via onNext()
  • Might be slow due to I/O, computation, or limited resources

The producer emits data (the Observable, Flowable, Publisher)
The consumer receives and handles it (your code in .subscribe())

🧪 Example:

Flowable.range(1, 1_000_000)      // ✅ Producer (fast)
    .observeOn(Schedulers.io())   // Shift to background thread
    .map(i -> {
        Thread.sleep(5);          // ⏳ Simulate slow work
        return i;
    })
    .subscribe(i -> {
        System.out.println("Consumed: " + i);  // 👈 Consumer
    });

Here, the Flowable is the producer — it emits 1 to 1,000,000 as fast as possible.

The .subscribe() block is the consumer — it processes each item slowly.

This mismatch = potential for backpressure problems.

🧠 Visualization:

  [Producer: Fast Stream]
      ───────▶ 1
      ───────▶ 2
      ───────▶ 3
      ...
        |
        | (Backpressure boundary)
        ▼
  [Consumer: Slow Subscriber]
      ◼️ Process 1 (slow)
      ◼️ Process 2 (slow)

The consumer gets overwhelmed unless:

  • You apply a backpressure strategy,
  • Or control the flow with a request(n) mechanism (in Flowable or Publisher),
  • Or buffer/delay/drop excess data.

💬 How Can You Identify the Consumer?

It’s any code that calls:

.subscribe(item -> {
    // 👈 This is the consumer
});

Or, in a more verbose style:

Observer<Integer> observer = new Observer<>() {
    public void onNext(Integer item) {
        // 👈 This is the consumer
    }
};

In Spring WebFlux, it would be your controller method or a service that consumes a Flux or Mono.

🧰 In Reactive Streams Spec Terms

ComponentRole
PublisherProducer
SubscriberConsumer
SubscriptionMiddleman that allows request(n) (backpressure control)
This entry was posted in Без рубрики. Bookmark the permalink.