0

我在处理由Stream.generate构造构建的通量时遇到问题。

Java 流正在从远程源获取一些数据,因此我实现了一个自定义供应商,其中嵌入了数据获取逻辑,然后使用它来填充流。

Stream.generate(new SearchSupplier(...))

我的想法是检测一个空列表并使用takeWhile->的Java9特性

Stream.generate(new SearchSupplier(this, queryBody))
            .takeWhile(either -> either.isRight() && either.get().nonEmpty())

(使用 Vavr 的 Either 构造)

然后,存储库层通量将执行以下操作:

return Flux.fromStream (
            this.searchStream(...) //this is where the stream gets generated
        )
        .map(Either::get)
        .flatMap(Flux::fromIterable);

“服务”层由通量上的一些转换步骤组成,但方法签名类似于Flux<JsonObject> search(...).

最后,控制器层有一个GetMapping:

@GetMapping(produces = "application/stream+json")
public Flux search(...) {
    return searchService.search(...) //this is the Flux<JsonObject> parth
         .subscriberContext(...) //stuff I need available during processing
         .doOnComplete(() -> log.debug("DONE")); 
}

我的问题是 Flux 似乎永远不会终止。例如,从 Postman 打来的电话只是在响应部分中拍摄了“正在加载...”部分。当我从我的 IDE 中终止该过程时,结果会被刷新到邮递员,我看到了我所期待的。doOnComplete lambda 也永远不会被调用

我注意到的是,如果我更改 Flux 的来源:

Flux.fromArray(...) //harcoded array of lists of jsons

doOnComplete lambda 被调用,http 连接也关闭,结果显示在邮递员中。

知道可能是什么问题吗?

谢谢。

4

1 回答 1

1

您可以使用如下所示的代码直接创建 Flux。请注意,我添加了一些假设的方法,您需要根据您的 SearchSupplier 的工作方式来实现这些方法:

Flux<SearchResultType> flux = Flux.generate(
            () -> new SearchSupplier(this, queryBody),
            (supplier, sink) -> {
                SearchResultType current = supplier.next();
                if (isNotLast(current)) {
                    sink.next(current);
                } else {
                    sink.complete();
                }
                return supplier;
            },
            supplier -> anyCleanupOperations(supplier)
        );
于 2019-01-24T06:35:06.293 回答