Reactive programming
Transform, map
Capitalize the user username, firstname and lastname
1
2
3
4
5
6
7
8Mono<User> capitalizeOne(Mono<User> mono) {
return mono.map(
u -> new User(
u.getUsername().toUpperCase(),
u.getFirstname().toUpperCase(),
u.getLastname().toUpperCase())
);
}Capitalize the users username, firstName and lastName
1
2
3
4
5
6
7
8
9
Flux<User> capitalizeMany(Flux<User> flux) {
return flux.map(
u -> new User(
u.getUsername().toUpperCase(),
u.getFirstname().toUpperCase(),
u.getLastname().toUpperCase())
);
}
flatMap
This new call can have latency so we cannot use the synchronous map anymore.
Instead, we want to represent the asynchronous call as a Flux or Mono, and use a different operator: flatMap.
즉
- map is for synchronous, non-blocking, 1-to-1 transformations
- flatMap is for asynchronous (non-blocking) 1-to-N transformations 변경하는 자체를 감싸고 있는 퍼블리셔이며 순서를 보장하지 않음
- // TODO Capitalize the users username, firstName and lastName using #asyncCapitalizeUser
1
2
3
4
5
6
7
8
Flux<User> asyncCapitalizeMany(Flux<User> flux) {
return flux.flatMap(this::asyncCapitalizeUser);
}
Mono<User> asyncCapitalizeUser(User u) {
return Mono.just(new User(u.getUsername().toUpperCase(), u.getFirstname().toUpperCase(), u.getLastname().toUpperCase()));
}
merge
- Merge flux1 and flux2 values with interleave
1 |
|
example1
2
3
4
5
Flux<Long> flux2 = Flux.just(100L, 101L, 102L);
flux1.mergeWith(flux2)
.doOnNext(System.out::println)
.blockLast();
- Merge flux1 and flux2 values with no interleave (flux1 values and then flux2 values)
if we want to keep the order of sources, we can use the concat
concat
1 |
|
- Create a Flux containing the value of mono1 then the value of mono2
1 | Flux<User> createFluxFromMultipleMono(Mono<User> mono1, Mono<User> mono2) { |