简体   繁体   English

Flux last() 为空时的操作

[英]Flux last() operation when empty

I am trying solve my problem when i need to get last element (last method) of a flux but in some cases these flux can be empty and the follow error is appear当我需要获取通量的最后一个元素(最后一种方法)时,我正在尝试解决我的问题,但在某些情况下,这些通量可能为空并且出现跟随错误

Flux#last() didn't observe any onNext signal

and this is the chain i have这是我的链条

return apiService.getAll(entry)
      .flatMap(response -> {
          if (response.getId() != null){
             //do some logic
             return Mono.just("some Mono");
          }
          else{
             return Mono.empty();
             }
          })
          .last()
          //more flatMap operators

I already use switchIfEmpty() as well but can't fix.我也已经使用switchIfEmpty()但无法修复。 What is the correct implementation to verify if can call last() or skip and return a empty to terminate chain operation.验证是否可以调用 last() 或跳过并返回空以终止链操作的正确实现是什么。

Thanks,谢谢,

According to Flux.last() api doc:根据Flux.last() api 文档:

emit NoSuchElementException error if the source was empty.如果源为空,则发出 NoSuchElementException 错误。 For a passive version use takeLast(int)对于被动版本使用takeLast(int)

It means that, for an empty upstream Flux:这意味着,对于一个空的上游 Flux:

  • last() will emit an error last()将发出错误
  • takeLast(1) will return an empty flux takeLast(1)将返回一个空的通量

Now, takeLast(1) returns a Flux, not a Mono, as last() does.现在, takeLast(1)返回一个 Flux,而不是像 last() 那样返回 Mono。 Then, you can just chain it with Flux.next() , and it will return the only retained value (if any), or propagate the empty signal.然后,您可以将它与Flux.next()链接起来,它将返回唯一保留的值(如果有),或者传播空信号。

Note: another solution would be to use last().onErrorResume(NoSuchElementException.class, err -> Mono.empty()) .注意:另一种解决方案是使用last().onErrorResume(NoSuchElementException.class, err -> Mono.empty()) This would catch the error sent by last() internally, and then return an empty mono. However, if you've got some code other than last() that can throw a NoSuchElementException , you might miss a problem.这会在内部捕获last()发送的错误,然后返回一个空的 mono。但是,如果您有除last()之外的一些代码可以抛出NoSuchElementException ,您可能会错过一个问题。 For this, my personal choice for your case would be to use takeLast(1).next() .为此,我个人对你的情况的选择是使用takeLast(1).next()

The following code example shows behavior of last() vs takeLast(1).next() :以下代码示例显示了 last() 与takeLast(1).next()的行为:

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class FluxLast {

    static void subscribe(Mono<?> publisher) {
        publisher.subscribe(value -> {},
                            err -> System.out.println("Failed: " + err.getMessage()),
                            () -> System.out.println("Completed empty"));
    }
    
    public static void main(String[] args) {
        subscribe(Flux.empty().last());
        subscribe(Flux.empty().takeLast(1).next());

        // When not empty, takeLast(1).next() will return the last value
        Integer v = Flux.just(1, 2, 3)
                            .takeLast(1)
                            .next()
                            .block();
        System.out.println("Last value: "+v);
    }
}

Program output:程序 output:

Failed: Flux#last() didn't observe any onNext signal from Callable flux
Completed empty
3

如何检查助焊剂<object>是空的还是不空的?<div id="text_translate"><p> 我有一个api供kube.netes调用检测服务是否可用。在api中,先调用一个接口获取其他服务的host,接口返回一个Flux,如果结果为空api返回SERVICE_UNAVAILABLE其他返回ok .我目前的代码如下:</p><pre class="lang-java prettyprint-override"> @GetMapping(value = "/gateway/readiness") public Mono<Long> readiness(ServerHttpResponse response) { Flux<Map<String, List<String>>> hosts = hostProvider.getHosts(); List<String> hostProviders = new ArrayList<>(); // the below code has a warning: Calling subscribe in a non-blocking scope hosts.subscribe(new Consumer<Map<String, List<String>>>() { @Override public void accept(Map<String, List<String>> stringListMap) { hostProviders.addAll(stringListMap.keySet()); } }); if (hostProviders.isEmpty()) { response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE); } return routeLocator.getRoutes().count(); }</pre><p> 有优雅做到这一点?</p></div></object> - How to check Flux<Object> is empty or not?

暂无
暂无

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

相关问题 助焊剂:如何测试空的助焊剂 - Flux:How to test empty Flux 助焊剂返回空对象 - Flux returns empty objects 与 Flux 相交操作 - Project Reactor - Intersect operation with Flux - Project Reactor 如何检查助焊剂<object>是空的还是不空的?<div id="text_translate"><p> 我有一个api供kube.netes调用检测服务是否可用。在api中,先调用一个接口获取其他服务的host,接口返回一个Flux,如果结果为空api返回SERVICE_UNAVAILABLE其他返回ok .我目前的代码如下:</p><pre class="lang-java prettyprint-override"> @GetMapping(value = "/gateway/readiness") public Mono<Long> readiness(ServerHttpResponse response) { Flux<Map<String, List<String>>> hosts = hostProvider.getHosts(); List<String> hostProviders = new ArrayList<>(); // the below code has a warning: Calling subscribe in a non-blocking scope hosts.subscribe(new Consumer<Map<String, List<String>>>() { @Override public void accept(Map<String, List<String>> stringListMap) { hostProviders.addAll(stringListMap.keySet()); } }); if (hostProviders.isEmpty()) { response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE); } return routeLocator.getRoutes().count(); }</pre><p> 有优雅做到这一点?</p></div></object> - How to check Flux<Object> is empty or not? 在一个通量<Flux<T> &gt;,如果是内Flux,如何完成外Flux<T> 最终是空的 - In a Flux<Flux<T>>, how to complete the outer Flux if the inner Flux<T> is eventually empty 当 Flux 完成时获取 Flux 大小 - Get Flux size when Flux is complete 当使用application / stream + json时,Spring Reactive WebFlux报告空流量 - Spring Reactive WebFlux reports empty flux when using application/stream+json 如何创建一个通量,其中通量的每个元素都是轮询操作并在成功或错误时终止通量? - How do I create a Flux where each element of the flux is a polling operation and terminate the flux on success or error? 在 spring web 中压缩两个独立的通量返回空 - Zipping two independent Flux in spring web Flux Returns Empty 磁通并行操作和阻塞任务在并行操作之后 - Flux parallel operation and a blocking task post the parallel operation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM