【问题标题】:Send multiple Fluxes with different types in one response在一个响应中发送多个不同类型的 Flux
【发布时间】:2021-06-05 10:30:26
【问题描述】:

如果我有这样的代码:

data class Response(
  val a: String,
  val b: List<String>,
  val c: Int,
)

fun buildResponse(): Response {
  val a: Mono<String> = getA()
  val b: Flux<String> = getB()
  val c: Mono<Int> = getC()

  return Response(
    a = a.blockOptional().orElseThrow(),
    b = b.collectList().blockOptional().orElseThrow(),
    c = c.blockOptional().orElseThrow(),
  )
}

有没有办法反应性地返回 Mono&lt;Response&gt; 而不是阻塞并返回实际的 Response

【问题讨论】:

  • 你看过zip操作符吗?
  • 不,你能输入一个简短的例子吗?
  • 当然,看我的回答。 (kotlin 语言标签可能也有助于在这里获得更快的答案。)

标签: kotlin spring-webflux project-reactor reactor


【解决方案1】:

当然 - 查看Mono.zip 运算符,它允许您将多个发布者合并到一个 Mono 中。基本的Mono.zip 变体只返回一个元组,但您也可以指定自己的类(在本例中为Response):

return Mono.zip(
        Function { eles: Array<Any> ->
            Response(eles[0] as String,
                    eles[1] as List<String>,
                    eles[2] as Int)
        },
        a, b.collectList(), c)

【讨论】:

    猜你喜欢
    • 2013-07-23
    • 2013-06-01
    • 2019-05-27
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多