【问题标题】:Wait the end of a subscription loop before returning value在返回值之前等待订阅循环的结束
【发布时间】:2018-10-09 11:57:34
【问题描述】:

我是响应式编程范式的新手。我有一个简单的问题。

我有一个元素列表,对于每个元素我都必须进行 REST 调用。

我必须根据这些调用的响应建立一个新列表。

问题是我的函数在循环结束之前返回值... 不知道怎么办?

这是我的一段代码:

TaeaUpdateRequestOutput putTaea(final String dossierId, final TaeaUpdateRequestInput input, final String token) {

    final TaeaUpdateRequestOutput output = new TaeaUpdateRequestOutput();

    input.getAdhesions().stream().forEach(adhesion -> {

        final Mono<TaeaFromMyMB> taeaResponse = doRest(adhesion, TaeaFromMyMB.class, url, token, dossierId);

        taeaResponse.subscribe(myMBTaea -> {
            final Taea taea = myMBTaea.fromTaeaFromMyMb(adhesion);
            output.getListeTaea().add(taea);
        });
    });
    //output is always empty due to async programming. How to wait the the end of the last iteration's subscription?
    return output;
}

【问题讨论】:

    标签: spring-webflux reactor


    【解决方案1】:

    您订阅了taeaResponses,但您没有等待订阅结果。

    试试类似的东西

        List<Taea> taeas = Flux.fromIterable(input.getAdhesions())
                .flatMap(adhesion -> doRest(adhesion, TaeaFromMyMB.class, url, token, dossierId)
                        .map(taeaFromMyMB -> taeaFromMyMB.fromTaeaFromMyMb(adhesion)))
                .collect(Collectors.toList())
                .subscribeOn(Schedulers.parallel())
                // wait result here
                .block();
    

    然后将其设置为输出。

    请记住,block() 会无限期等待,因此您可以使用reactor.core.publisher.Mono#block(java.time.Duration) 来避免它。

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多