Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple Monos into a flux

I am appending a Flux with a flatMap, but if I add additional flatMaps, only the last one gets returned.

// Here is an example of the Mono function

private Mono<MyType> appendFirstMono(Group group) {
    return Mono.just(group)
    .map(MyType::new)
        .flatMap(g -> functionZ(group)
        .map(g::setField));
} 


//This works as expected

public Flux<MyType> function1() {

    return returnData(id)
            .thenMany(service.getData(id))
            .flatMap(this::appendFirstMono);
}

//This does not and only returns the last mono (3rd)

public Flux<MyType> function1() {

    return returnData(id)
            .thenMany(service.getData(id))
            .flatMap(this::appendFirstMono)
            .flatMap(this::appendSecondMono)
            .flatMap(this::appendThirdMono);
}

//I've attempted to fix with this... Doesn't work as expected.   

public Flux<MyType> function1() {

    return returnData(id)
            .thenMany(service.getData(id))
            .flatMap(x -> {
                return Flux.merge(
                    appendFirstMono(x),
                    appendSecondMono(x),
                    appendThirdMono(x)
                );
            });
}

I need to process each Mono function on the flux but I can't seem to get each to execute and return properly.

like image 940
xman77 Avatar asked Oct 22 '25 17:10

xman77


1 Answers

You can try concat to process the mono one by one check out my example

        Flux.concat(getMono(0),getMono(1),getMono(2))
            .map(integer -> {
                System.out.println(integer);
                return integer;
            })
            .subscribe();

}

private Mono<Integer> getMono(Integer a) {
    return Mono.just(a)
            ;
}

this will print 0,1,2

like image 145
Ricard Kollcaku Avatar answered Oct 25 '25 09:10

Ricard Kollcaku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!