transform vs transformDeferred
Asked Answered
P

1

6

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

Partible answered 2/9, 2020 at 18:57 Comment(1)
read about hot and cold publishers projectreactor.io/docs/core/release/reference/… you switch between them using the deferred keyword.Crosslegged
N
17

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.

Nigh answered 10/9, 2020 at 10:34 Comment(1)
Did I get it right? If I call transform() with loggingTrait = f -> f.log(serviceName + "@" + System.currentTimeMillis()); then each subscriber will log the same time and it will be the time when transform() called?Subroutine

© 2022 - 2024 — McMap. All rights reserved.