How to deal with two Fluxes in Spring Reactive Programing?

徘徊边缘 提交于 2019-12-25 01:48:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!