反应流中的单声道与助焊剂 [英] Mono vs Flux in Reactive Stream

查看:199
本文介绍了反应流中的单声道与助焊剂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档:

助焊剂是一种可以发射0..N个元素的流:

Flux is a stream which can emit 0..N elements:

Flux<String> fl = Flux.just("a", "b", "c");

单声道是0..1个元素的流:

Mono is a stream of 0..1 elements:

Mono<String> mn = Mono.just("hello");

这也是反应流中Publisher接口的实现.

And as both are the implementations of the Publisher interface in the reactive stream.

在大多数情况下我们不能仅使用Flux吗,因为它也可以发射0..1,从而满足Mono的条件?

Can't we use only Flux in most of the cases as it also can emit 0..1, thus satisfying the conditions of a Mono?

或者仅当需要使用Mono且Flux无法处理这些操作时,是否存在某些特定条件? 请提出建议.

Or there are some specific conditions when only Mono needs to be used and Flux can not handle the operations? Please suggest.

推荐答案

在许多情况下,您正在进行一些计算或调用服务,并且您希望得到的只是一个结果(或者可能是零个或一个结果),而不是一个预期的结果可能包含多个结果.在这种情况下,使用Mono更为方便.

In many cases, you are doing some computation or calling a service and you expect exactly one result (or maybe zero or one result), and not a collection that contains possibly multiple results. In such cases, it's more convenient to have a Mono.

将其与常规" Java进行比较:不会将List用作可以返回零或一个结果的任何方法的返回类型.您应该改用Optional,这样可以立即清楚地表明,您期望得到的结果不止一个.

Compare it to "regular" Java: you would not use List as the return type of any method that can return zero or one result. You would use Optional instead, which makes it immediately clear that you do not expect more than one result.

这篇关于反应流中的单声道与助焊剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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