簡體   English   中英

如何實現具有可完成未來的具有 Mono/Flux 的 Reactive Framework 中存在的.switchIfEmpty() 類型的方法?

[英]How do I achieve .switchIfEmpty() type of method present in Reactive Framework with Mono/Flux with completable future?

Mono<String> getData1(){
  return someApiClient.getData();
}

Mono<String> getData2(){
  return someCacheClient.getData();
}

Mono<Object> callingMethod(){
  return getData2().switchIfEmpty(getData1());
}

如果我的實現是這樣的,我該如何轉換“callingMethod”

CompletableFuture<String> getData1(){
  return someApiClient.getData().toFuture();
}

CompletableFuture<String> getData2(){
  return someCacheClient.getData().toFuture();
}

CompletableFuture<String> callingMethod(){
  // How to do it here? I am not getting any way. 
  // I need to achieve similar functionality like .switchIfEmpty here
}

我試圖在網上搜索不同的文章,但沒有找到。 請幫幫我。

與 Reactor 類型不同, CompletableFuture能夠處理null值,因此您可以使用它來表示空的 state 並基於此執行操作:

CompletableFuture<String> callingMethod(){
    return getData2()
        .thenCompose(cached -> cached == null 
            ? getData1() 
            : CompletableFuture.completedFuture(cached));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM