Lab 06: Reactive Streams

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm zchencow/innozverse-java:latest bash


Overview

Java 9+ ships the Reactive Streams specification as java.util.concurrent.Flow. Learn to build Publisher/Subscriber pipelines with backpressure, compose Processor stages, handle errors, and understand how RxJava/Project Reactor implement these same interfaces.


Step 1: Reactive Streams Specification

Reactive Streams (RS) contracts:
  1. Publisher<T>     — produces items, respects demand
  2. Subscriber<T>    — consumes items
  3. Subscription     — token controlling demand
  4. Processor<T,R>   — both Publisher AND Subscriber

Flow:
  Publisher.subscribe(Subscriber)
  → onSubscribe(Subscription)    // subscriber receives subscription
  → Subscription.request(n)      // subscriber requests n items
  → onNext(item) × n             // publisher emits up to n items
  → onComplete() | onError(t)    // terminal signal

Backpressure rule:
  Publisher MUST NOT emit more than request(n) items

Step 2: SubmissionPublisher — Built-in Publisher


Step 3: Backpressure — Controlled Demand

📸 Verified Output:


Step 4: Custom Publisher Implementation

💡 The drain() loop is the heart of a Publisher — it emits items respecting demand while checking for cancellation.


Step 5: Processor — Transform Pipeline


Step 6: Error Handling and Cancellation


Step 7: Comparison — Flow vs RxJava vs Reactor


Step 8: Capstone — Full Reactive Pipeline

📸 Verified Output:


Summary

Concept
Interface/Class
Key Method

Publisher

Publisher<T>

subscribe(Subscriber)

Subscriber

Subscriber<T>

onNext/onError/onComplete

Subscription

Subscription

request(n), cancel()

Processor

Processor<T,R>

Both Publisher and Subscriber

Built-in publisher

SubmissionPublisher<T>

submit(), close()

Backpressure

Subscription.request(n)

Demand-driven flow control

Error propagation

closeExceptionally()

onError() called

Cancellation

Subscription.cancel()

Stop receiving items

Last updated