24 Şubat 2021 Çarşamba

SpringWebFlux Mono.doOnNext metodu

Giriş
Açıklaması şöyle
Mono::doOnNext triggers when the data is emitted successfully, which means the data is available and present.

Mono::doOnSuccess triggers when the Mono completes successfully - result is either T or null, which means the processing itself successfully finished regardless the state of data and is executed although the data are not available or present but the pipeline itself succeed.

Mono::then as the end of the methods chain returns Mono<Void> on complete and error signals.
Örnek
Şöyle yaparız
Mono.just(5)
  .doOnNext(i -> logger.info(i + ""))     // <-- is called and prints '5'
  .flatMap(i -> Mono.empty())
  .doOnNext(i -> logger.info(i + ""))     // <-- is NOT called
  .doOnSuccess(i -> logger.info("Done"))  // <-- is called and prints 'Done' (i is null)
  .block();
Örnek
Elimizde şöyle bir kod olsun. service::update() çalışmaz. Çünkü o da bir Mono dönüyor ve bu dönülen Mono nesnesine subscribe olunmadı
interface Service {
Mono<String> create(String s);
Mono<Void> update(String s);
}
class Foo {
private final Service service;
Mono<Void> problem() {
return service
.create("foo")
.doOnNext(service::update)
.then();
}
}
Düzeltmek için şöyle yaparız
interface Service {
Mono<String> create(String s);
Mono<Void> update(String s);
}
class Foo {
private final Service service;
Mono<Void> problem() {
return service
.create("foo")
.doOnNext(foo -> service.update(foo).block())
.then();
}
}
Açıklaması öyle
The take away here is to only use doOn* methods for side-effects, e.g. logging, uploading metrics.

Hiç yorum yok:

Yorum Gönder