Do a CompletionStage inside a CompletionStage

66 views Asked by At

We have an internal API that executes the code in a lambda and returns a Boolean result in a CompleteStage:

private CompletionStage<Boolean> foo1() {
    return internalAPI(param -> {
        // first step
        // second step
        return Boolean.TRUE;
    });
}

Now the second step is implemented as an async task as well:

private CompletionStage<Boolean> foo2() {
    return internalAPI(param -> {
        // first step
        secondStep();  // <-- how to execute this and get result of it?
        // if second step finished successfully then ... 
        return Boolean.TRUE;
    });
}

private CompletionStage<Boolean> secondStep() {
    // do something
}

How do I make the secondStep() run in the foo2(), make sure it's finished before hitting return Boolean.TRUE;?

--- EDIT ---

This is the brief implementation of internalAPI(), basically it's trying to do all steps in one transaction and if one of the steps is failed the transaction can be rollback:

public <A> CompletableFuture<A> internalAPI(Function<Connection, A> block) {
    return CompletableFuture.supplyAsync(() -> doTransaction(block),
            new HttpExecutionContext(databaseContext).current());
}

public <T> T doTransaction(Function<Connection, T> block) {
    Transaction tx = Ebean.beginTransaction();
    try (Connection sql2oConnection = sql.open()) {
        spliceConnections(sql2oConnection, tx.getConnection());
        T ret = block.apply(sql2oConnection);
        Ebean.commitTransaction();
        return ret;
    } finally {
        Ebean.endTransaction();
    }
}
0

There are 0 answers