Reputation: 41
I need to implement this function:
// 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()));
}
My implementation:
return flux
.map(user -> asyncCapitalizeUser(user))
.flatMap(Mono::flux)
Is this correct, and can it be improved?
Upvotes: 3
Views: 3067
Reputation: 121272
Just this is enough:
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) {
Upvotes: 3