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