Search code examples
reactive-programmingspring-reactivespring-reactorspring-kotlin

return Mono/Flux with 2 nested subscriptions


I need to return Mono / Flux for a function but this has 2 nested subscriptions. I am looking for a better solution to publish Mono/Flux only after this 2 subscription values are available then perform some operation to derieve finalValue.

The final Objective is, The subscribers of the function getFinalValue() should be able to subscribe to final value. I have a similar need for Flux also. What should be the best approach to do this?

fun <T> getFinalValue(): Mono<T> {

    object1.getValue1().subscribe { value1 ->

        object2.getValue2(value1.id).subscribe{ value2 -> 

        // perform some operation with value 1 and 2
        // derieve finalValue
       }
   } 

 return //I need to return Mono<T> which should publish finalValue to the subscribers of this function. 

}


Solution

  • You can use .cache() to store value1 and move forward with Mono.zip. Then in zip flatMap you have tuple with value1 and value2

    fun <T> getFinalValue(): Mono<T> {
        val value1 = object1.getValue1().cache();
        val value2 = object1.getValue1().flatMap(value -> object2.getValue2(value));
    
        return Mono.zip(value1, value2)
                .flatMap(tuple -> {
            // logic with tuple.T1 and tuple.T2
        })
    }