0

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. 

}

Ashok Krishnamoorthy
  • 853
  • 2
  • 14
  • 24

2 Answers2

1

Did you want to do like it?

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

    return object1.getValue1()
        .flatMap { value1 ->

            object2.getValue2(value1.id)
                .map { value2 ->
                    // perform some operation with value 1 and 2
                    // derieve finalValue
                }
        }
}

Jongho Jeon
  • 96
  • 1
  • 3
  • This works fine if getvalue1, getValue2 and finalValue all are Mono or all are Flux. If it is a mix then it is becoming difficult. Though this works, Solution suggested by @mslowiak sounds relatively better. Thank you anyway for your time ! – Ashok Krishnamoorthy May 11 '20 at 20:29
1

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
    })
}
mslowiak
  • 1,688
  • 12
  • 25