Search code examples
spring-webfluxproject-reactorreactive-streamsspring-reactor

transform vs transformDeferred


What is the difference between transform & transformDeferred in project reactor flux.

Good example will be helpful.

https://projectreactor.io/docs/core/release/reference/index.html#advanced-mutualizing-operator-usage


Solution

  • Most of the time, a Flux is "lazy": you declare a processing pipeline, but data only starts flowing once you subscribe to it. You can subscribe multiple times.

    This is called a cold Flux (and each time you subscribe to a cold source, the source generates its data anew for the benefit of the new subscriber).

    So we can distinguish:

    • assembly time: the moment where we call operators on a Flux instance, returning a new Flux instance
    • subscription time: the moment where that instance is subscribed to. Actually, the moments (plural), since there could be multiple subscriptions which could be far apart.

    transform is a convenience method to apply a set of operators to a given Flux. For instance, you want all your Flux returned by methods of a service to use .log("serviceName"), so you externalize this trait in a static Function<Flux, Flux>:

    loggingTrait = f -> f.log("serviceName");`

    Now you can apply this trait in all Flux-returning methods of the service via transform.

    It is applied immediately, right at assembly time. Since subscribers come after, they all "share" the same result of the function.

    Now imagine you'd like the logging to eg. include the time of subscription, or another piece of data that is more dependent on each individual subscriber.

    That's where transformDeferred comes in: it defers the application of the Function to the moment where the subscription occurs. Plus, it applies the Function for EACH subscription.

    So you could do something like:

    loggingTrait = f -> f.log(serviceName + "@" + System.currentTimeMillis());
    

    And the logs category would be different for each subscriber.