transform vs transformDeferred

主宰稳场 提交于 2021-02-08 10:10:41

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/63711972/transform-vs-transformdeferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!