从Mono列表中创建助焊剂的正确方法 [英] Proper way to create a Flux from a list of Mono's

查看:112
本文介绍了从Mono列表中创建助焊剂的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个使用CustomObjects列表的API操作.对于这些对象中的每个对象,它调用一个服务方法来创建一个Mono.如何以惯用的,因此无阻塞的方式从那些Mono对象创建助焊剂?

Lets say I have a API operation that consumes a List of CustomObjects. For every one of those objects it calls a service method that creates a Mono. How do I create a Flux from those Mono objects in an idiomatic and therefore non-blocking way?

我现在想出的是这个.我更改了方法名称以更好地反映其预期目的.

What I've come up with for now is this. I changed the method names to better reflect their intended purpose.

fun myApiMethod(@RequestBody customObjs: List<CustomObject>): Flux<CustomObject> {

    return Flux.create { sink ->
        customObjs.forEach {

            service.persistAndReturnMonoOfCustomObject(it).map {
                sink.next(it)
            }
        }
        sink.complete()
    }
}

此外,我是否需要订阅助焊剂才能真正使它返回某些东西?

Moreover do I need to subscribe to the flux to actually make it return something?

推荐答案

我相信您可以改用concat():

/**
 * Concatenate all sources provided as a vararg, forwarding elements emitted by the
 * sources downstream.
 * <p>
 * Concatenation is achieved by sequentially subscribing to the first source then
 * waiting for it to complete before subscribing to the next, and so on until the
 * last source completes. Any error interrupts the sequence immediately and is
 * forwarded downstream.
 * <p>
 * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.3.RELEASE/src/docs/marble/concat.png" alt="">
 * <p>
 * @param sources The {@link Publisher} of {@link Publisher} to concat
 * @param <T> The type of values in both source and output sequences
 *
 * @return a new {@link Flux} concatenating all source sequences
 */
@SafeVarargs
public static <T> Flux<T> concat(Publisher<? extends T>... sources) {

merge():

/**
 * Merge data from {@link Publisher} sequences contained in an array / vararg
 * into an interleaved merged sequence. Unlike {@link #concat(Publisher) concat},
 * sources are subscribed to eagerly.
 * <p>
 * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.3.RELEASE/src/docs/marble/merge.png" alt="">
 * <p>
 * Note that merge is tailored to work with asynchronous sources or finite sources. When dealing with
 * an infinite source that doesn't already publish on a dedicated Scheduler, you must isolate that source
 * in its own Scheduler, as merge would otherwise attempt to drain it before subscribing to
 * another source.
 *
 * @param sources the array of {@link Publisher} sources to merge
 * @param <I> The source type of the data sequence
 *
 * @return a merged {@link Flux}
 */
@SafeVarargs
public static <I> Flux<I> merge(Publisher<? extends I>... sources) {

这篇关于从Mono列表中创建助焊剂的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆