【问题标题】:Converting a while loop to Reactive Java将 while 循环转换为反应式 Java
【发布时间】:2022-10-07 22:53:29
【问题描述】:

我在 Java 中使用 Project Reactor。我将如何以反应方式编写这个阻塞while循环?

  Flux<Instant> findHistory() {
    int max = 10;
    Instant lastSeenTime = Instant.now();

    List<Instant> instants = new ArrayList<>();
    AtomicInteger pageNumber = new AtomicInteger(1);

    while (instants.size() < max) {
      List<Instant> block =
          getHistory(pageNumber.getAndIncrement())
              .filter(instant -> instant.isBefore(lastSeenTime))
              .collectList()
              .block();

      instants.addAll(block);
    }
    return Flux.fromIterable(instants);
  }

  Flux<Instant> getHistory(int pageNumber) {
    // returns the page of Instants
  }

我想继续调用getHistory,将过滤后的结果添加到我的列表instants,直到该列表的大小为max。我曾尝试使用repeatWhenexpand,但还没有弄清楚如何使用它们来实现这个while 循环的作用。

【问题讨论】:

  • 我自己无法对此进行测试,因此我不会将其写为完整答案,但作为提示,我认为您想使用.take(max)

标签: java reactive-programming repeat reactive


【解决方案1】:

最终使用 take 如下

   Flux<Instant> findHistory() {
        int max = 10;
        Instant lastSeenTime = Instant.now();

        return Flux.range(1, Integer.MAX_VALUE)
                .flatMap(pg -> getHistory(pg))
                .filter(instant -> instant.isBefore(lastSeenTime))
                .take(max);
    }

    Flux<Instant> getHistory(int pageNumber) {
        // returns the page of Instants
    }

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2018-02-22
    • 2017-04-26
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多