简体   繁体   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());
}

How do I convert the "callingMethod" if my implementation is like this如果我的实现是这样的,我该如何转换“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
}

I tried to search different articles online but did not find any.我试图在网上搜索不同的文章,但没有找到。 Please help me out here.请帮帮我。

Unlike Reactor types, CompletableFuture is able to handle null values, so you can use that to represent empty state and do action based on that:与 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