Chaining several CompletionStage only if a condition is achieved

后端 未结 3 1456
无人共我
无人共我 2020-12-29 06:40

I have several CompletionStage methods that I\'d like to chain. The problem is that the result of the first one will determine if the next ones should be execut

3条回答
  •  佛祖请我去吃肉
    2020-12-29 07:04

    If you have to check only for null values you can solve using Optional. For example you should do:

    public Bar execute(String id) {
    
          return this.getFooById(id)
                .thenCompose(this::checkFooPresent)
                .thenCompose(this::doSomethingElse)
                .thenCompose(this::doSomethingElseMore)
                .thenApply(rankRes -> new Bar(foo));
    
    }
    
    
    private Optional getFooById(String id) {
    
        // some better logic to retrieve foo
    
        return Optional.ofNullable(foo);
    }
    
    
    private CompletableFuture checkFooPresent(Optional optRanking) {
    
        CompletableFuture future = new CompletableFuture();
        optRanking.map(future::complete).orElseGet(() -> future.completeExceptionally(new Exception("Foo not present")));
        return future;
    }
    

    The checkFooPresent() receives an Optional, and if its value is null it complete exceptionally the CompletableFuture.

    Obviously you need to manage that exception, but if you have previously setted an ExceptionHandler or something similar it should come for free.

提交回复
热议问题