将Flux转换为Mono,在Mono上执行方法,然后再将其转换回Flux。

3
我需要实现这个函数:
// 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)  

这是否正确,还能改进吗?

1个回答

3

仅仅这些就足够了:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接