【问题标题】:Transform Flux to Mono, execute method on Mono and transform back to Flux将 Flux 转换为 Mono,在 Mono 上执行方法并转换回 Flux
【发布时间】:2017-12-27 03:58:23
【问题描述】:

我需要实现这个功能:

// 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)  

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

【问题讨论】:

    标签: project-reactor


    【解决方案1】:

    这样就够了:

    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) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 2020-01-28
      • 1970-01-01
      • 2020-10-04
      • 2017-06-19
      • 2022-08-19
      • 1970-01-01
      • 2018-11-28
      相关资源
      最近更新 更多