问题描述
transform
和有什么区别?transformDeferred
在项目反应堆通量中.
What is the difference between transform
& transformDeferred
in project reactor flux.
好的例子会有帮助.
https://projectreactor.io/docs/core/release/reference/index.html#advanced-mutualizing-operator-usage
推荐答案
大多数时候,Flux
是懒惰的":你声明一个处理管道,但数据只有在您订阅后才会开始流动.您可以多次订阅.
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.
这称为 cold Flux
(每次您订阅冷源时,源都会为新订阅者的利益重新生成其数据).
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).
所以我们可以区分:
- 组装时间:我们在
Flux
实例上调用运算符的时刻,返回一个新的Flux
实例 - 订阅时间:订阅该实例的时刻.实际上,是时刻(复数),因为可能存在多个相距很远的订阅.
- assembly time: the moment where we call operators on a
Flux
instance, returning a newFlux
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
是一种将一组运算符应用于给定 Flux
的便捷方法.例如,您希望服务方法返回的所有 Flux
都使用 .log("serviceName")
,因此您可以在 static函数
:
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");`
loggingTrait = f -> f.log("serviceName");`
现在您可以通过 transform
在服务的所有 Flux 返回方法中应用此特征.
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.
这就是 transformDeferred
的用武之地:它将 Function
的应用推迟到订阅发生的那一刻.此外,它还为每个订阅应用了 Function
.
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.
所以你可以这样做:
loggingTrait = f -> f.log(serviceName + "@" + System.currentTimeMillis());
每个订阅者的日志类别都会不同.
And the logs category would be different for each subscriber.
这篇关于变换与变换延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!