How to chain API call responses with Mutiny (Uni's)

457 Views Asked by At

I have 3 reactive rest client functions getOne(): Uni<String>, getTwo(reponseFromOne): Uni<List<Two>>, getThree(responsesFromTwo): Uni<List<Three>>

I want to chain them so the result from getOne is passed as argument to getTwo and results from getTwo are passed as arguments to getThree. So that I can construct objects after all calls are passed

Something like .. the following pseudo code..

val someObjects: Uni<List<SomeObject> =
    getOne().onItem().transformToUni { input -> getTwo(input) }
        .onItem().transformToUni { input2 -> getThree(input2) }
        .map {
            SomeObject(getTwo.something, getThree.something)
        }
1

There are 1 best solutions below

2
Kirill Byvshev On

Nick, hello! You can chain such functions with flatMap. I've tried to implement your example in the format of unit-test.

@Test
void chainTest() {
    var someObject = getOne()
            .flatMap(input1 -> getTwo(input1)
                    .flatMap(input2array -> Multi.createFrom().iterable(input2array)
                            .onItem().transformToUniAndConcatenate(input2 -> getThree(input2)
                                    .map(input3 -> new SomeObject(input1, input2, input3)))
                            .collect().asList()
                    ))
            .await().indefinitely();
}