Implementing Reactive Programming

1. Implementing Reactive Streams

InterfaceRole
PublisherEmits items
SubscriberReceives items
SubscriptionControls demand (request/cancel)
ProcessorBoth publisher and subscriber

2. Using Mono and Flux

Example: Project Reactor

Mono<User> one = userRepo.findById(id);          // 0..1
Flux<Order> many = orderRepo.findByUser(id);     // 0..N

Flux.range(1, 5)
    .map(i -> i * 2)
    .filter(i -> i > 4)
    .subscribe(System.out::println);

3. Implementing Reactive Operators

OperatorUse
mapTransform 1:1
flatMapTransform with async result
filterKeep matching
zipCombine N streams item-wise
merge / concatCombine sequentially / concurrently
switchIfEmptyDefault when empty
retryWhenConditional retry

4. Handling Backpressure

StrategyDetail
BUFFERQueue items (memory risk)
DROPDiscard newest
LATESTKeep only most recent
ERRORSignal overflow
request(n)Pull-based control

5. Implementing Reactive Repositories

Example: R2DBC repository

public interface OrderRepository extends ReactiveCrudRepository<Order, UUID> {
    Flux<Order> findByCustomerId(UUID customerId);
    Mono<Long> countByStatus(String status);
}

6. Implementing Reactive Web Controllers

Example: WebFlux

@RestController @RequestMapping("/orders")
public class OrderController {
    @GetMapping("/{id}")
    public Mono<Order> get(@PathVariable UUID id) { return service.findById(id); }
    @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Order> stream() { return service.streamAll(); }
}

7. Handling Reactive Error Handling

OperatorUse
onErrorReturnDefault value on error
onErrorResumeSwitch to alternate publisher
onErrorMapTranslate exception
retry / retryWhenRetry on error
doOnErrorSide effect (logging)

8. Implementing Reactive Composition

Example: Combine sources

Mono<OrderDetails> details = Mono.zip(
        orderService.findById(id),
        customerService.findByOrderId(id),
        shippingService.estimate(id))
    .map(t -> new OrderDetails(t.getT1(), t.getT2(), t.getT3()));

9. Implementing Reactive Testing

Example: StepVerifier

StepVerifier.create(service.findById(id))
    .expectNextMatches(o -> o.id().equals(id))
    .verifyComplete();

StepVerifier.create(failing)
    .expectError(NotFoundException.class)
    .verify();

10. Handling Schedulers

SchedulerUse
Schedulers.parallel()CPU-bound; size = cores
Schedulers.boundedElastic()Blocking I/O
Schedulers.single()Single thread
subscribeOnWhere source runs
publishOnWhere downstream runs

11. Implementing Reactive Caching

OperatorUse
cache()Replay all values to late subscribers
cache(Duration)TTL-based
CacheMonoExternal-cache-backed

12. Implementing Reactive Security

ConcernDetail
SecurityWebFilterChainWebFlux equivalent of HttpSecurity
ReactiveSecurityContextHolderContext propagated via reactor context
@PreAuthorizeReturns Mono/Flux; checks before subscribe
Note: Java 21 virtual threads NEW often beat reactive for typical web apps with simpler code.