Deluxxx
Deluxxx

Reputation: 180

Generate Flux<Result> from two Flux

I'm working now with Flux. I want create one Flux<Result> from two different objects Flux. I know I have to use BiFunction but I don't know how. First object have PK and second FK to first object. I want zip that object which the PK=FK.

Description problem: I have a case at work where I have a list of houses and a list in which I was. I need to return the result with all the houses, I will only change the true / false flag on the Result object. The second list of course may have fewer elements.

Can anyone suggest something like that or any other way?

@RunWith(SpringRunner.class)
@SpringBootTest

public class WholesaleControllerTest {

@Test
public void testZipFlux() {
    Flux<Flux1> flux1 = Flux.just(new Flux1(1, "test1"), new Flux1(2, "test2"), new Flux1(3, "test3"));
    flux1.subscribe(item -> System.out.println("Flux1 " + item));
    Flux<Flux2> flux2 = Flux.just(new Flux2(2, true), new Flux2(1, false), new Flux2(3, true));
    flux2.subscribe(item -> System.out.println("Flux2 " + item));


    Flux<Result> = ...//TODO zip flux1 and flux2 to RESULT

}

@Getter
@Setter
@AllArgsConstructor
class Flux1{
    private int id;
    private String value;
}

@Getter
@Setter
@AllArgsConstructor
class Flux2{
    private int id_fk_flux2;
    private boolean value;
}


@Getter
@Setter
@AllArgsConstructor
class Result{
    private int id;
    private String flux1Value;
    private boolean flux2Value;
}

}

Upvotes: 4

Views: 1462

Answers (1)

pvpkiran
pvpkiran

Reputation: 27078

This is one way to do. But I have to say, this is not strictly reactive programming(because I am using block on first flux to create a map).

Having said that, I cannot think of any other way

Map<Integer, Flux1> flux1Map = flux1.collectMap(Flux1::getId, Function.identity()).block();

Flux<Result> results = flux2.flatMap(item -> {
        //TODO : Handle cases like key not found in flux1
        Flux1 entry = flux1Map.get(item.getId_fk_flux2());
        Result result = new Result(entry.getId(), entry.getValue(), item.isValue());
        return Mono.just(result);
    }).collectList().flatMapMany(Flux::fromIterable);

Upvotes: 1

Related Questions