首页 > 解决方案 > 如何在 Flux.subscribe 之后收集数据以将其作为 json 数组发送?

问题描述

这是我做的一个例子,我应该怎么做才能让处理后的数据将结果列表作为 WS json 响应发送?

    @Produces(MediaType.APPLICATION_JSON)
     public List<String> tryFlux(@QueryParam("names") List<String> names) {
         String[] array = new String[names.size()];
         Flux.fromIterable(asList(names.toArray(array))).
                 doOnNext(this::executeService).doOnError(ex -> handleError(ex, names)).retry(1).subscribe();
         return ??; //Need help here
      }

标签: javaspringreactor

解决方案


您可以使用 Mono 包装已解析的值以返回 JSON 数据。

  @Produces(MediaType.APPLICATION_JSON)
 public Mono<JSONResponseObject> tryFlux(@QueryParam("names") List<String> names) {
     String[] array = new String[names.size()];
     Flux.fromIterable(asList(names.toArray(array))).
             doOnNext(this::executeService).doOnError(ex -> handleError(ex, names)).retry(1).subscribe();
     return Mono.just(jsonResponseObject); //Need help here
  }

推荐阅读