Skip to content

Commit

Permalink
Add Async bind to link two Async together.
Browse files Browse the repository at this point in the history
  • Loading branch information
neilcsmith-net committed Dec 9, 2024
1 parent 654eb71 commit 540f996
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,24 @@ private void unlink(Link<T> link) {
}
}

/**
* Bind a target Async to complete when a source Async completes. When the
* source Async completes, the target will be completed with the same result
* or error.
*
* @param <T> result type
* @param source source async
* @param target target async
*/
public static <T> void bind(Async<T> source, Async<? super T> target) {
Objects.requireNonNull(target);
if (source.done()) {
complete(source, target);
} else {
source.link(handler(async -> complete(async, target)));
}
}

/**
* Create an Async that will complete when the provided async call
* completes, by extracting the first call argument and attempting to map to
Expand Down Expand Up @@ -239,6 +257,14 @@ public static <T> CompletableFuture<T> toCompletableFuture(Async<T> async) {
}
}

private static <T> void complete(Async<T> source, Async<? super T> target) {
if (source.failed()) {
target.fail(source.error());
} else {
target.complete(source.result());
}
}

private static <T> void completeExtract(Async<Call> asyncCall, Async<T> asyncValue, Class<T> type, int argIdx) {
try {
if (asyncCall.failed()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,31 @@ public void testError() {
assertNull(async.result());
}

@Test
public void testBind() {
Async<String> source = new Async<>();
Async<Object> target = new Async<>();
Async.bind(source, target);
source.complete("FOO");
assertTrue(target.done());
assertEquals("FOO", target.result());

source = new Async<>();
target = new Async<>();
source.complete("BAR");
Async.bind(source, target);
assertTrue(target.done());
assertEquals("BAR", target.result());

source = new Async<>();
target = new Async<>();
Async.bind(source, target);
PError error = PError.of("ERROR");
source.fail(error);
assertTrue(target.done());
assertSame(error, target.error());
}

@Test
public void testExtractArg() {
// Test Value extract
Expand Down Expand Up @@ -144,15 +169,15 @@ public void testToCompletableFuture() {
asyncString.fail(PError.of(ex));
assertTrue(futureString.isCompletedExceptionally());
assertSame(ex, futureString.exceptionNow());

// error before link
asyncString = new Async<>();
ex = new Exception("FOO");
asyncString.fail(PError.of(ex));
futureString = Async.toCompletableFuture(asyncString);
assertTrue(futureString.isCompletedExceptionally());
assertSame(ex, futureString.exceptionNow());

// test queued and future
asyncString = new Async<>();
futureString = Async.toCompletableFuture(asyncString);
Expand Down

0 comments on commit 540f996

Please sign in to comment.