project-reactor - 将 Flux 转换为 Mono,在 Mono 上执行方法并转换回 Flux

标签 project-reactor

我需要实现这个功能:

// TODO Capitalize the users username, firstName and lastName 
// using #asyncCapitalizeUser method below

Flux<User> asyncCapitalizeMany(Flux<User> flux) {

}

Mono<User> asyncCapitalizeUser(User u) {
    return Mono.just(
            new User(u.getUsername().toUpperCase(),
                    u.getFirstname().toUpperCase(),
                    u.getLastname().toUpperCase()));
}

我的实现:

return flux
    .map(user -> asyncCapitalizeUser(user))
    .flatMap(Mono::flux)  

这是否正确,是否可以改进?

最佳答案

这就足够了:

return flux
        .flatMap(this::asyncCapitalizeUser);

/**
 * Transform the elements emitted by this {@link Flux} asynchronously into Publishers,
 * then flatten these inner publishers into a single {@link Flux} through merging,
 * which allow them to interleave.
 * <p>
 * There are three dimensions to this operator that can be compared with
 * {@link #flatMapSequential(Function) flatMapSequential} and {@link #concatMap(Function) concatMap}:
 * <ul>
 *     <li><b>Generation of inners and subscription</b>: this operator is eagerly
 *     subscribing to its inners.</li>
 *     <li><b>Ordering of the flattened values</b>: this operator does not necessarily preserve
 *     original ordering, as inner element are flattened as they arrive.</li>
 *     <li><b>Interleaving</b>: this operator lets values from different inners interleave
 *     (similar to merging the inner sequences).</li>
 * </ul>
 * <p>
 * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.0.M3/src/docs/marble/flatmap.png" alt="">
 * <p>
 * @param mapper the {@link Function} to transform input sequence into N sequences {@link Publisher}
 * @param <R> the merged output sequence type
 *
 * @return a new {@link Flux}
 */
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {

enter image description here

关于project-reactor - 将 Flux 转换为 Mono,在 Mono 上执行方法并转换回 Flux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231901/

相关文章:

spring-boot - 将Mono流转换为Flux

spring-webflux - react 堆句柄运算符返回对象?

java - Spring 网 react 无法表现出背压

java - 如何等待List中的所有Monos完成(成功与否无关紧要)

spring-webflux - 从 Mono.fromCallable 返回 Mono.empty()

java - 单声道异步异常处理

javascript - 我应该如何更新 *.eslintrc* 到 ESLint 以查看更改?

reactive-programming - 抛出异常作为 react 流验证的最正确方法

spring - 何时使用Mono <List <Object >>以及何时将Flux <Object>用于RestController方法

java - 我可以对 subscribeOn 方法和异步任务使用相同的执行器吗