DEV Community

chintanpuggalok
chintanpuggalok

Posted on

Implementing Context Propagation in Reactive Programming Projects πŸ”„

Learn how to seamlessly propagate context through a reactive stream in your project using Project Reactor, an essential skill for modern Java developers working with reactive programming models.

Mono<DemoClass> demoClassMono = Mono.just(demoObject)
    // Add context to MDC (Mapped Diagnostic Context) for logging purposes on each signal πŸ“‹
    .doOnEach(signal -> {
        logUtil.addToMdc(signal.getContextView());
    })
    // Transform the Mono stream by applying a function to each item emitted πŸ”„
    .transform(demoClassMono1 -> {
        log.info("inside main post init {}", demoClassMono1.toString());
        return another.anotherDemoProcess(demoClassMono1);
    })
    // Write context information by adding header details to the Reactor context ✍
    .contextWrite(context -> {
        return context.putAllMap(headerDetails);
    });
Enter fullscreen mode Exit fullscreen mode

Key Concepts Explained πŸ”‘

  • .doOnEach((signal) -> {...}): This operator allows for side-effects, such as logging, to be performed for each signal (onNext, onError, onComplete) in the stream. Utilizing logUtil.addToMdc(signal.getContextView()) ensures that every emitted item enriches the Mapped Diagnostic Context (MDC), making it easier to trace and debug reactive chains. πŸ“Š

  • .contextWrite(context -> {...}): By leveraging this operator, developers can modify the context propagated down the stream. Adding key-value pairs from the headerDetails map into the Reactor context with context.putAllMap(headerDetails) is a powerful way to include essential metadata, like request IDs or user tokens, throughout the reactive pipeline. πŸ”§

Why It Matters in Reactive Programming 🌟

Understanding and implementing context propagation in reactive programming is pivotal for maintaining a clear and traceable execution flow, especially in complex, asynchronous systems. These techniques improve debugging, logging, and the management of metadata across asynchronous boundaries, enhancing the overall reliability and maintainability of applications built with Project Reactor.

here is a Git repo for an example
Git repo for context propagation

Top comments (0)