Reactive programming

Transform, map

  1. Capitalize the user username, firstname and lastname

    1
    2
    3
    4
    5
    6
    7
    8
    Mono<User> capitalizeOne(Mono<User> mono) {
    return mono.map(
    u -> new User(
    u.getUsername().toUpperCase(),
    u.getFirstname().toUpperCase(),
    u.getLastname().toUpperCase())
    );
    }
  2. 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 변경하는 자체를 감싸고 있는 퍼블리셔이며 순서를 보장하지 않음
  1. // 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

  1. Merge flux1 and flux2 values with interleave
1
2
3
4

Flux<User> mergeFluxWithInterleave(Flux<User> flux1, Flux<User> flux2) {
return flux1.mergeWith(flux2);
}

example

1
2
3
4
5

Flux<Long> flux2 = Flux.just(100L, 101L, 102L);
flux1.mergeWith(flux2)
.doOnNext(System.out::println)
.blockLast();

  1. 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
2
3
4

Flux<User> mergeFluxWithNoInterleave(Flux<User> flux1, Flux<User> flux2) {
return flux1.concatWith(flux2);
}
  1. Create a Flux containing the value of mono1 then the value of mono2
1
2
3
Flux<User> createFluxFromMultipleMono(Mono<User> mono1, Mono<User> mono2) {
return Flux.concat(mono1, mono2);
}