简体   繁体   English

将 while 循环转换为 Reactive Java

[英]Converting a while loop to Reactive Java

I am using Project Reactor in Java. How would I write this blocking while loop in a reactive way?我在 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
  }

I want to keep calling getHistory add the result after filtering to my list instants until that list has the size of max .我想继续调用getHistory将过滤后的结果添加到我的列表中, instants该列表的大小为max I have tried to use repeatWhen and expand but haven't figure out how to use them to achieve what this while loop does.我曾尝试使用repeatWhenexpand但还没有弄清楚如何使用它们来实现 while 循环的功能。

Ended up using take as follows最终使用 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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM