如何在 Java Spring 上等待订阅者完成 TEXT_EVENT_STREAM

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

使用返回字符串的 Stream API 时,我想要一个函数将它们返回到由定界符分隔的单个字符串上,当前使用订阅并附加到列表,但显然,因为异步不会等待它准备好返回该功能之前。

如何实现非异步方法?

private String executeStream(String streamId, UserToken currentUserAndToken) {

    List<String> combinedString = new ArrayList<String>();

    URI streamUri = UriComponentsBuilder.newInstance()
        .scheme("https")
        .host(host)
        .path(streamPath)
        .buildAndExpand(streamVariablesMap)
        .toUri();

    webClientt.get()
        .uri(streamUri)
        .headers(h -> h.setBearerAuth(currentUserAndToken.getToken()))
        .accept(MediaType.TEXT_EVENT_STREAM) // for Server-Sent Events (SSE)
        .retrieve()
        .bodyToFlux(String.class) // convert the response body to a Flux
        .subscribe(data -> combinedString.add(data)); // < --- Here I want to combine all Data into single string

    return String.join(", ", combinedString);
}
java spring spring-boot stream
1个回答
0
投票

使用 .blockLast() 代替 .subscribe() 它将阻塞,直到你读完所有。这将使您的呼叫同步。请参阅https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#blockLast--

© www.soinside.com 2019 - 2024. All rights reserved.