spotify / completable-futures

Utilities for working with futures in Java 8
Apache License 2.0
393 stars 51 forks source link

Would a short-circuiting function be useful here? #50

Open davidxia opened 7 years ago

davidxia commented 7 years ago

I have two futures A and B. If A finishes first and is false, for example, I want to short-circuit and return false without waiting for B. If B returns first, however, I still want to wait on A. Could we add such a function here?

davidxia commented 7 years ago

Does this already exist somewhere? If not, any plans on supporting this? Or it a "PRs welcome :)" thing?

davidxia commented 7 years ago

@dflemstr @mbruggmann

mbruggmann commented 7 years ago

@davidxia I haven't encountered this case before (nor could I come up with an existing implementation right now), but it sounds useful. Can you propose it as a PR?

krka commented 7 years ago

So what you want is something like:

CompletableFuture<A> a;
CompletableFuture<B> b;
return a.thenApply(x -> {
  if (b.isDone()) {
   // do something with both A and B
  } else {
   // do something only with A
  }
}

If a helper function for this usecase would be significantly shorter and easier to read perhaps it's worth adding.

eshrubs commented 7 years ago

Or something like this?

  public static <F, T> CompletionStage<T> shortCircuit(
          final CompletionStage<F> first,
          final Predicate<F> shouldContinue,
          final CompletionStage<T> second) {
    return dereference(first.handle((f, throwable) -> {
      if (throwable != null || !shouldContinue.test(f)) {
        second.toCompletableFuture().cancel(true);
        return exceptionallyCompletedFuture(new RuntimeException());
      }
      return second;
    }));
  }
mattnworb commented 4 years ago

@davidxia is this still something you want to track with an open issue?

davidxia commented 4 years ago

Feel free to close

On Wed, Jan 22, 2020 at 16:43 Matt Brown notifications@github.com wrote:

@davidxia https://github.com/davidxia is this still something you want to track with an open issue

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/spotify/completable-futures/issues/50?email_source=notifications&email_token=AADVK3LV776VORBLLO2X6PLQ7C4WXA5CNFSM4DAJOQX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEJVGYCA#issuecomment-577399816, or unsubscribe https://github.com/notifications/unsubscribe-auth/AADVK3JPOA2A5UPPMPRMRPLQ7C4WXANCNFSM4DAJOQXQ .

-- David Xia Software Engineer dxia@spotify.com