问题
I have two Fluxes
Flux<Foo> foo;
Flux<Bar> bar;
class Foo
String id
String prop1
String barId
class Bar
String barId
String color
boolean isInFoo
foo and bar both have barId property. The size of foo is always equal to or less than size of bar but usually it is much less than bar size (number of Bars in Flux. For example Foo could represent a few selected items out of a basket of Bar items although the two are different objects.
Bar has a boolean flag isInFoo with default value = false, which is set to true if Foo has that barId.
How to iterate through bar and find if each bar has a barId in foo and if so set isInFoo to true.
I also have available
Mono<Foo> findByBarId(String barId) {}
in addition to above Flux<Foo> findAll() {}
Note that findByBarId and findAll are expensive database operations.
回答1:
Suppose you have following two flux:
Flux<Foo> foos;
Flux<Bar> bars;
You can modify the Flux of Bar objects as follows:
bars.flatMap(bar -> findByBarId(bar.getBarId())
.flatMap(foo -> {
bar.setIsInFoo(true);
return Mono.just(bar);
}).switchIfEmpty(Mono.just(bar)));
来源:https://stackoverflow.com/questions/50778089/how-to-deal-with-two-fluxes-in-spring-reactive-programing