completable-futures icon indicating copy to clipboard operation
completable-futures copied to clipboard

Would a short-circuiting function be useful here?

Open davidxia opened this issue 8 years ago • 7 comments

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 avatar Feb 15 '17 23:02 davidxia

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

davidxia avatar Jun 15 '17 20:06 davidxia

@dflemstr @mbruggmann

davidxia avatar Jun 15 '17 20:06 davidxia

@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?

mbruggmann avatar Jun 16 '17 07:06 mbruggmann

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.

krka avatar Jul 10 '17 10:07 krka

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;
    }));
  }

eshrubs avatar Jul 25 '17 21:07 eshrubs

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

mattnworb avatar Jan 22 '20 21:01 mattnworb

Feel free to close

On Wed, Jan 22, 2020 at 16:43 Matt Brown [email protected] 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 [email protected]

davidxia avatar Jan 22 '20 21:01 davidxia