0

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.

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
ace
  • 11,526
  • 39
  • 113
  • 193

1 Answers1

3

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)));
uneq95
  • 2,158
  • 2
  • 17
  • 28
  • the second `flatMap` is superfluous, you could change that to a simple `map`, as `setIsInFoo` isn't expensive nor async. – Simon Baslé Jun 11 '18 at 11:45
  • actually not even a `map`, just a `.doOnNext(bar -> bar.setIsInFoo(true))`, to simply mutate the `bar`. Note you probably don't want to return `Mono.just` in a `map` (that gives you a `Flux>`) – Simon Baslé Jun 11 '18 at 15:42
  • But the method findByBarId returns a Mono of Foo, not a Bar. If we get a foo from that call, then only we have to transform the bar object. – uneq95 Jun 11 '18 at 15:46
  • ah right, misunderstood the original usecase. so your flatMap in flatMap makes more sense then, sorry – Simon Baslé Jun 11 '18 at 16:01
  • uneq95 this does not work, no mutation occurs in bars even though there are some foos that have the barId. When I try bars = your answer now bars contains only those bars for which isInFoo is true, I am lost again. – ace Jun 12 '18 at 18:46
  • @ace I have edited the answer. If the findByBarId returns Mono.empty() then just return that bar as it is, using switchIfEmpty(). – uneq95 Jun 12 '18 at 19:52
  • uneq95 works now! but I did have to do bars = your answer otherwise in place mutation does not happen, – ace Jun 13 '18 at 04:41