Webflux Reactor如何合并Stream.map输出,可以是Mono和Flux成Flux

问题描述 投票:0回答:1

A
用于获取源。在下面的
map
函数中,如果
Flux
拥有源,则源是
a
,否则源是
Mono
。函数返回基于 A 的 List 可以查询的所有源,列表大小可以为 1。问题是当 Stream.map 输出可以是两者之一时,如何处理这个 Mono 和 Flux 组合为 Flux。

class A {
    String x;
    String y;
    boolean isOwner();
}

Flux<Source> foo(List<A> a) {
  Flux<Source> sources = a.stream().map(v -> if (v.isOwner) {
        Flux<Source> ownedSource = ...; return ownedSource;
      } else {
        Mono<Source> givenSource = ...; return givenSource;
      }
    }.???
  return sources;
}
spring-webflux project-reactor
1个回答
0
投票

您可以将其用作

Flux
flatMap
:

Flux<Source> foo(List<A> a) {
  Flux<Source> sources = Flux.fromIterable(a)
    .flatMap(v -> if (v.isOwner) {
        Flux<Source> ownedSource = ...; return ownedSource;
      } else {
        Mono<Source> givenSource = ...; return givenSource;
      }
    }
  return sources;
}
© www.soinside.com 2019 - 2024. All rights reserved.