简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM