如何将 Mono<List<Type>> 转换为 Flux<Type>?

6
使用Spring 5,结合Reactor,我们有以下需求。
Mono<TheResponseObject> getItemById(String id){
    return webClient.uri('/foo').retrieve().bodyToMono(TheResponseObject)
}

Mono<List<String>> getItemIds(){
    return webClient.uri('/ids').retrieve().bodyToMono(List)
}

Mono<RichResonseObject> getRichResponse(){
    Mono<List> listOfIds = Mono.getItemIds()
    listOfIds.each({ String id ->
        ? << getItemById(id) //<<< how do we convert a list of ids in a Mono to a Flux
    })
    Mono<Object> someOtherMono = getOtherMono()
    return Mono.zip((? as Flux).collectAsList(), someOtherMono).map({
        Tuple2<List, Object> pair ->
        return new RichResonseObject(pair.getT1(), pair.getT2())
    }).cast(RichResonseObject)
}

有哪些方法可以将 Mono<List<String>> 转换为 Flux<String>?
2个回答

13

这应该可以运行。在单个字符串列表中给定。

  Mono<List<String>> listOfIds;

  Flux<String> idFlux = listOfIds
    .flatMapMany(ids -> Flux.fromArray(ids.toArray(new String [0])));

更好的是

listOfIds.flatMapMany(Flux::fromIterable)

2
你应该使用 Flux.fromIterable() 而不是创建两个新数组。 - Leonard Brünings
我们遇到的问题是类型转换 - 同时将Mono转换为Flux。就像你提到的flatMapMany方法一样,它解决了这个问题。感谢您的建议 - 它对我们很有帮助! - Bas Kuis
我将尝试更清晰地重新表述问题,然后很高兴选择这个答案。现在我清楚了这里发生的事情:ids.toArray(new String[0]))。 - Bas Kuis

2
请查看以下代码: 首先将 Mono<List<String>> 转换为 Flux<List<String>>,然后再将 Flux<List<String>> 转换为 Flux<String>
List<String> asList = Arrays.asList("A", "B", "C", "D");
Flux<String> flatMap = Mono.just(asList).flux().flatMap(a-> Flux.fromIterable(a));

或者您可以使用flatmapmany
Flux<String> flatMapMany = Mono.just(asList).flatMapMany(x-> Flux.fromIterable(x));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接