首页 > 解决方案 > 如何调用所有`Mono` 同时

问题描述

我想同时调用所有Mono并获取所有值。但是下面的代码不足以满足这两个要求。如何实施?

@Test
fun test1() {
    val m1 = Mono.delay(Duration.ofSeconds(3)).thenReturn("v1").log()
    val m2 = Mono.delay(Duration.ofSeconds(3)).thenReturn("v2").log()

    // waits in 3 seconds but cannot get returned values
    val result = Mono.`when`(m1, m2).block()
    assertNull(result)
}

@Test
fun test2() {
    val m1 = Mono.delay(Duration.ofSeconds(3)).thenReturn("v1").log()
    val m2 = Mono.delay(Duration.ofSeconds(3)).thenReturn("v2").log()

    // can get returned value but requires 6 seconds to process
    val result = Flux.concat(m1, m2).collectList().block()
    assertEquals(listOf("v1", "v2"), result)
}

标签: javakotlinrx-javareactive-programming

解决方案


您可以使用以下zip功能:

val result = Mono.zip(m1, m2).block()

推荐阅读