Skip to content
This repository has been archived by the owner on Sep 27, 2023. It is now read-only.

feat: add ApiFutures.catchingAsync #117

Merged
merged 2 commits into from Mar 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/main/java/com/google/api/core/ApiFutures.java
Expand Up @@ -104,6 +104,27 @@ public static <V, X extends Throwable> ApiFuture<V> catching(
return new ListenableFutureToApiFuture<V>(catchingFuture);
}

@BetaApi
public static <V, X extends Throwable> ApiFuture<V> catchingAsync(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overal looks good to me, but can we mark this as @Beta API just in case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

ApiFuture<V> input,
Class<X> exceptionType,
final ApiAsyncFunction<? super X, V> callback,
Executor executor) {
ListenableFuture<V> catchingFuture =
Futures.catchingAsync(
listenableFutureForApiFuture(input),
exceptionType,
new AsyncFunction<X, V>() {
@Override
public ListenableFuture<V> apply(X exception) throws Exception {
ApiFuture<V> result = callback.apply(exception);
return listenableFutureForApiFuture(result);
}
},
executor);
return new ListenableFutureToApiFuture<>(catchingFuture);
}

public static <V> ApiFuture<V> immediateFuture(V value) {
return new ListenableFutureToApiFuture<>(Futures.<V>immediateFuture(value));
}
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/com/google/api/core/ApiFuturesTest.java
Expand Up @@ -83,6 +83,24 @@ public Integer apply(Exception ex) {
assertThat(fallback.get()).isEqualTo(42);
}

@Test
public void testCatchAsync() throws Exception {
SettableApiFuture<Integer> future = SettableApiFuture.<Integer>create();
ApiFuture<Integer> fallback =
ApiFutures.catchingAsync(
future,
Exception.class,
new ApiAsyncFunction<Exception, Integer>() {
@Override
public ApiFuture<Integer> apply(Exception ex) {
return ApiFutures.immediateFuture(42);
}
},
directExecutor());
future.setException(new Exception());
assertThat(fallback.get()).isEqualTo(42);
}

@Test
public void testTransform() throws Exception {
SettableApiFuture<Integer> inputFuture = SettableApiFuture.<Integer>create();
Expand Down