Reputation: 4795
In a reactor operation chain, it first queries another server for response, and then based on response fields, it continues reactor Mono
chain or stops. Before using reactor, I often use if else
to control whether it continues. However, the following code would throw NPE for map(any -> null)
. I can put body of the next map
into if else
, but it is not a reactor chain in that way. So how to stop reactor operation chain based on validation of data? Basically, I wish it could be Mono.empty
when map(any -> null)
private Mono<MyResponse> post() {
return client.post()
.uri("/somepath")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(new MyRequest(), MyRequest.class)
.retrieve()
.bodyToMono(MyResponse.class);
}
Slice<MyEntity> allBy = myRepository.findAll(pageable);
Flux.fromIterable(allBy.getContent())
.flatMap(entity -> {
return this.post()
.map(response-> {
String img = response.getImg();
if (img ==null || img.equals("")) {
return null;
} else {
return new AnotherVo();
}
})
.map(anotherVo-> {
entity.setField(anotherVo.getField());
myRepository.save(entity);
return 1;
});
}).reduce(Integer::sum)
.block();
Upvotes: 2
Views: 988
Reputation: 67
Maybe what you are looking for is to use filter operation based on some attribute. E.g.:
.flatMap(entity -> {
return this.post()
.filter(response-> response.getImg() != null && !response.getImg().equals(""))
.map(any -> {
var anotherVo = new AnotherVo();
entity.setField(anotherVo.getField());
myRepository.save(entity);
return 1;
});
})
Note that the map will only be executed if the filter emits some non-empty signal. If you want to add a fallback value, just use .switchIfEmpty(value)
Upvotes: 1