如何在java中使用Mono创建条件循环?

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

我需要在反应式管道中有一个条件循环。只要条件为真,它就应该继续循环,一旦条件变为假,它就应该停止循环并返回从循环中获得的任何值。

Mono.just(new Pair<>(record, order))
            .flatMap(pair -> handleDelayedRoundNumber()
                    .flatMap(roundNumber -> handleProofRequest(pair.first(), pair.second())
                            .doOnSuccess(proof -> new Pair<>(roundNumber < order.clientMetadata().timeout(), proof))
                    )
            ).repeat(result -> result.first() && result.second() != null)
            .flatMap(result -> {
                if(result.second() == null){
                    return Mono.empty();
                }
                return Mono.just(result.second());
            })
            .flatMap(proof -> doStuffWithProof(proof));

我需要像这样的东西。但我不知道该怎么做。

我认为我想要的想法更容易用非反应器方式解释

Order order = ...;
Record record = ...;
String proof;
do {
   int roundNumber = handleDelayedRoundNumber();
   proof = handleProofRequest(record, order);
while(roundNumber < order.clientMetadata().timeout() && proof == null);

doStuffWithProof(proof);
java project-reactor
1个回答
0
投票

我想你正在寻找这样的东西:

// just create an infinite flow, like a while loop
Flux.range(0, Long.MAX_VALUE)
   .flatMap {
        handleDelayedRoundNumber()
          // here we check when to complete the processing, like in the while loop
          .takeUntil { roundNumber -> order.clientMetadata().timeout() }
          .handleProofRequest(record, order)
   }
   // stop once we've got an element; or nothing
   .next()
© www.soinside.com 2019 - 2024. All rights reserved.