[英]Flux last() operation when empty
當我需要獲取通量的最后一個元素(最后一種方法)時,我正在嘗試解決我的問題,但在某些情況下,這些通量可能為空並且出現跟隨錯誤
Flux#last() didn't observe any onNext signal
這是我的鏈條
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
我也已經使用switchIfEmpty()
但無法修復。 驗證是否可以調用 last() 或跳過並返回空以終止鏈操作的正確實現是什么。
謝謝,
根據Flux.last()
api 文檔:
如果源為空,則發出 NoSuchElementException 錯誤。 對於被動版本使用takeLast(int)
這意味着,對於一個空的上游 Flux:
last()
將發出錯誤takeLast(1)
將返回一個空的通量現在, takeLast(1)
返回一個 Flux,而不是像 last() 那樣返回 Mono。 然后,您可以將它與Flux.next()
鏈接起來,它將返回唯一保留的值(如果有),或者傳播空信號。
注意:另一種解決方案是使用last().onErrorResume(NoSuchElementException.class, err -> Mono.empty())
。 這會在內部捕獲last()
發送的錯誤,然后返回一個空的 mono。但是,如果您有除last()
之外的一些代碼可以拋出NoSuchElementException
,您可能會錯過一個問題。 為此,我個人對你的情況的選擇是使用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);
}
}
程序 output:
Failed: Flux#last() didn't observe any onNext signal from Callable flux
Completed empty
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.