Flux / Mono 常用方法和技巧

flatMap

Flux、Mono 里面都有 flatMap 方法。flatMap 方法是干什么的呢?我的理解是:flatMap 对 Flux、Mono 里面的元素逐个处理转换成另一个 Publisher,然后再将这些 publishers 合并成一个新的 Flux、Mono 对象返回。

flatMap function in Flux/Mono is used to transform each element emitted by a Publisher into another Publisher, and then flatten these inner publishers into a single Flux/Mono。

但是一个很重要的知识点是,flatMap 的转换,需要 subscribe(…) 触发,也就是说如果没有 subscribe(…) 触发,flatMap 的转换就不会进行。

Flux 的 flatMap 方法:

Mono 的 flatMap 方法:

一个很关键的问题是: flatMap 操作是异步的吗?

网上每个答案都告诉你,flatMap 是异步的,但是在我的学习测试过程中,并没有测出来 flatMap 的异步现象,比如上面的 test2() 方法,我在最后一步输出那里打断点,则前面的代码没有执行完是不会走到走后一步的,虽然这种测试异步的方式不严谨,但我一次也遇到过例外情况。

flatMapMany

flatMapMany 是 Mono 里面的方法,Flux 里面没有。

flatMapMany in Reactor is a powerful operator that transforms each item emitted by a Mono into a Publisher, and then flattens these publishers into a single Flux. This can be particularly useful for transforming data in a reactive stream or chaining asynchronous operations.

flatMapMany 是将 Mono 发射的每个元素转换成一个 Publisher ,再将这个 Publisher 合并一个 Flux。

Here are some examples to demonstrate how to use flatMapMany.

Example 1: Simple flatMapMany Usage

In this example, we use flatMapMany to transform a Mono of a list of items into a Flux of individual items.

flatMapMany 可以将一个 Mono<List<E>> 转换成只包含一个元素的 Flux<E> 。

Example 2: flatMapMany with Asynchronous Operations

In this example, we use flatMapMany to transform a Mono into a Flux of items that each undergo an asynchronous operation.

flatMapMany 可以

Example 3: flatMapMany for Network Calls

In this example, flatMapMany is used to perform multiple network calls for each item in a Mono.

Example 4: Error Handling with flatMapMany

In this example, we demonstrate how to handle errors within flatMapMany.

Example 5: Complex Data Processing with flatMapMany

In this example, we use flatMapMany to process complex data structures.

Explanation:

  1. Example 1: Demonstrates how to convert a Mono containing a list into a Flux of individual items.
  2. Example 2: Demonstrates asynchronous processing of each item in a Mono.
  3. Example 3: Demonstrates making network calls for each item in a Mono.
  4. Example 4: Demonstrates error handling within flatMapMany.
  5. Example 5: Demonstrates processing complex data structures with flatMapMany.

These examples should help you understand how to use flatMapMany effectively in different scenarios.

码先生
Author: 码先生

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注