DEV Community


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 -> {
    // Transform the Mono stream by applying a function to each item emitted 🔄
    .transform(demoClassMono1 -> {"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)