Skip to content

Commit

Permalink
Add Awaitable#all(List) and Awaitable#any(List) (#338)
Browse files Browse the repository at this point in the history
  • Loading branch information
slinkydeveloper authored Jun 3, 2024
1 parent 1e8d250 commit 787a13e
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions sdk-api/src/main/java/dev/restate/sdk/Awaitable.java
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,28 @@ public static AnyAwaitable any(Awaitable<?> first, Awaitable<?> second, Awaitabl
awaitables);
}

/**
* Create an {@link Awaitable} that awaits any of the given awaitables.
*
* <p>An empty list is not supported and will throw {@link IllegalArgumentException}.
*
* <p>The behavior is the same as {@link
* java.util.concurrent.CompletableFuture#anyOf(CompletableFuture[])}.
*/
public static AnyAwaitable any(List<Awaitable<?>> awaitables) {
if (awaitables.isEmpty()) {
throw new IllegalArgumentException("Awaitable any doesn't support an empty list");
}
return new AnyAwaitable(
awaitables.get(0).syscalls,
awaitables
.get(0)
.syscalls
.createAnyDeferred(
awaitables.stream().map(Awaitable::deferred).collect(Collectors.toList())),
awaitables);
}

/**
* Create an {@link Awaitable} that awaits all the given awaitables.
*
Expand All @@ -130,6 +152,31 @@ public static Awaitable<Void> all(
return single(first.syscalls, first.syscalls.createAllDeferred(deferred));
}

/**
* Create an {@link Awaitable} that awaits all the given awaitables.
*
* <p>An empty list is not supported and will throw {@link IllegalArgumentException}.
*
* <p>The behavior is the same as {@link
* java.util.concurrent.CompletableFuture#allOf(CompletableFuture[])}.
*/
public static Awaitable<Void> all(List<Awaitable<?>> awaitables) {
if (awaitables.isEmpty()) {
throw new IllegalArgumentException("Awaitable all doesn't support an empty list");
}
if (awaitables.size() == 1) {
return awaitables.get(0).map(unused -> null);
} else {
return single(
awaitables.get(0).syscalls,
awaitables
.get(0)
.syscalls
.createAllDeferred(
awaitables.stream().map(Awaitable::deferred).collect(Collectors.toList())));
}
}

static class SingleAwaitable<T> extends Awaitable<T> {

private final Deferred<T> deferred;
Expand Down

0 comments on commit 787a13e

Please sign in to comment.