反应流中的Mono与Flux
收藏

根据文档:

助焊剂是可以发射0..N个元素的流:
Flux<String> fl = Flux.just("a", "b", "c");
Mono是0..1元素的流:
Mono<String> mn = Mono.just("hello");

两者都是反应流中Publisher接口的实现。

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

还是有某些特定条件,当仅需要使用Mono且Flux无法处理操作时? 请提出建议。

最佳答案

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.

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.

    公众号
    关注公众号订阅更多技术干货!