Mono

Represents 0 to 1 elements

Pasted image 20220912195315.png

Instance methods

block

Convert from Mono<T> to T. Retrieve value of the Mono. For example:

public User monoToValue(Mono<User> userMono) {  
  return userMono.block();  
}
@Test  
void monoToValue_success() {  
  var user = blockingApp.monoToValue(Mono.just(new User("Austin")));  
  assertThat(user.username).isEqualTo("Austin");  
}

defaultIfEmpty

If the Mono is empty then return a default value.

static Mono<User> emptyToDefault(Mono<User> user) {  
  return user.defaultIfEmpty(new User("default user"));  
}
static void emptyToDefaultMain() {  
  emptyToDefault(Mono.empty()).subscribe(System.out::println); // default user  
}
> Task :app:OtherOperationApp.main()
username: default user
firstname: null
lastName: null

Static methods

firstWithValue

Return the one that is faster will be returned.

static Mono<User> fasterUserMono(Mono<User> userMono1, Mono<User> userMono2) {  
  return Mono.firstWithValue(userMono1, userMono2);  
}
static void fasterUserMonoMain() throws InterruptedException {  
  CountDownLatch countDownLatch = new CountDownLatch(1);  
  
  fasterUserMono(  
      Mono.just(new User("austin")).delayElement(Duration.ofMillis(100)),  
      Mono.just(new User("test2")).delayElement(Duration.ofMillis(50))  
  ).doFinally((t) -> countDownLatch.countDown()).subscribe(System.out::println);  
  
  countDownLatch.await();  
}

Will output the test2

> Task :app:OtherOperationApp.main()
username: test2
firstname: null
lastName: null

justOrEmpty

If it's null then return a Mono.empty() instead

static Mono<User> nullAwareUserToMono(User user) {  
  return Mono.justOrEmpty(user);  
}
static void nullAwareUserToMonoMain() {
  nullAwareUserToMono(null).subscribe(System.out::println); // should not print
  nullAwareUserToMono(new User("austin")).subscribe(System.out::println); // should print
}
> Task :app:OtherOperationApp.main()
username: austin
firstname: null
lastName: null