如何同时调用所有的`Mono <E>

时间:2019-09-03 04:51:28

标签: java kotlin rx-java reactive-programming

我想同时调用所有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)
}

1 个答案:

答案 0 :(得分:1)

您可以使用zip函数:

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