javakotlinreactor

Chain Multiple Reactor Monos


I am new to reactive programming and it may happen that this question is easily solvable or I am doing something completely wrong. Let us consider following interface

interface NumbersOperator{fun apply(value:Double,value2:Double):Mono<Double>}

implementation

class Plus(val name:String):NumbersOperator{
  fun apply(value:Double,value2:Double):Mono<Double>{
    return Mono.just(value+value2)    
}
}

At the moment I have a list of `

val plusOperators = listOf(Plus("first"), Plus("second"), Plus("third"))

` and the way how i combine the operators is the following

fun combine():Mono<Double>{
  val first=plusOperators.firstOrNull(it.name=="first")
  val second=plusOperators.firstOrNull(it.name=="second")
  val third=plusOperators.firstOrNull(it.name=="third")

  return first.apply(1.0,1.0).map{it*1.0}.flatMap{second.apply(it,1.0)}.map{it*1.0}.flatMap{third.apply(it,1.0)}
 
}

At the moment i can live with this but it would be much easier and more generic if I could just create the above chain from the list of plusOperators. Please be noted, this is just a simplification of what i am doing, basically i have to map result from previous and to call another mono and so on


Solution

  • You could just fold your operator list, like this:

    fun combine(): Mono<Double> {
        val plusOperators = listOf(Plus("first"), Plus("second"), Plus("third"))
        return plusOperators.fold(Mono.just(1.0)) { acc, op ->
            acc.flatMap { op.apply(it, 1.0) }
        }
    }