Flux和Mono中的compose()vs.transform()vs.as()vs.map() [英] compose() vs. transform() vs. as() vs. map() in Flux and Mono

查看:202
本文介绍了Flux和Mono中的compose()vs.transform()vs.as()vs.map()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我决定尝试使用 projectreactor.io (io.projectreactor:3.1.1)的Spring 5.

Recently, I decided to try spring 5 with projectreactor.io (io.projectreactor:3.1.1).

有人知道使用此功能的最佳情况是什么?使用它们中的每一个有什么优点和缺点?应该在哪里使用它们?

好的例子会有所帮助.

推荐答案

您在这里有两种截然不同的运算符类别:

You have two broadly different categories of operators here:

当您定期组成运算符链并且您的应用程序中具有通用的运算符使用模式时,可以使用composetransform互操作此代码或为它指定一个更具描述性的名称.

When you compose chains of operators regularly and you have common operator usage patterns in your application, you can mutualize this code or give it a more descriptive name by using compose and transform.

两者之间的区别是何时应用互有运算符:transform在实例化时应用它们,而compose在订阅时应用它们(允许动态选择添加的运算符).

The difference between the two is when the mutualized operators are applied: transform applies them at instantiation, while compose applies them at subscription (allowing for dynamic choice of the added operators).

看看参考文档以获取更多详细信息和示例.

Have a look at the reference documentation for more details and examples.

这是在整个Flux上应用Function的同时使整个代码保持流利样式的便捷快捷方式.一个示例是将其转换为Mono(如javadoc中所示),但它也可以帮助以工厂方法样式实现的外部运算符.

This is a convenience shortcut to apply a Function to the whole Flux while keeping the whole code in a fluent style. An example would be to convert to a Mono (as shown in the javadoc), but it can also helps with external operators that are implemented in a factory method style.

reactor-addons MathFlux为例,并进行比较:

Take reactor-addons MathFlux for example, and compare:

MathFlux.sumInt(Flux.range(1, 10)
                    .map(i -> i + 2)
                    .map(i -> i * 10))
        .map(isum -> "sum=" + isum);

收件人:

Flux.range(1, 10)
    .map(i -> i + 2)
    .map(i -> i * 10)
    .as(MathFlux::sumInt)
    .map(isum -> "sum=" + isum)

(这可以帮助您处理一个事实,与Kotlin不同,Java没有扩展方法:))

map都是关于数据的.当源中的每个元素可用时,它将1-1转换函数应用于它们.

map is all about the data. It applies a 1-1 transformation function to each element in the source, as they become available.

在上面的MathFlux示例中,map依次用于将2与每个原始整数相加,然后再次将序列中的每个数字乘以10,然后第三次从末尾产生String每笔款项.

In the MathFlux example above, map is successively used to add 2 to each original integer, then again to multiply each number in the sequence by 10, then a third time at the end to produce a String out of each sum.

这篇关于Flux和Mono中的compose()vs.transform()vs.as()vs.map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆