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

Commit

Permalink
feat: add @BetaApi ApiFutures.catchingAsync (#117)
Browse files Browse the repository at this point in the history
Add new ApiFuture.catchingAsync method mirroring ApiFuture.catching, except allowing for an ApiAsyncFunction to be passed instead of ApiFunction.

I tried to match the existing signature that allows the callback to return '? extends V' but this does not seem to be possible (see transformAsync).
  • Loading branch information
schmidt-sebastian committed Mar 13, 2020
1 parent f9320c3 commit 8d40a11
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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(
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

0 comments on commit 8d40a11

Please sign in to comment.