
mutiny.zero.AsyncHelpers Maven / Gradle / Ivy
package mutiny.zero;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
public interface AsyncHelpers {
/**
* Creates a failed completion stage.
*
* @param t the failure
* @param the emitted type
* @return the failed completion stage.
* @deprecated Use {@link CompletableFuture#failedFuture(Throwable)} instead, this helper method was here while Java 8
* compatibility was required.
*/
@Deprecated(forRemoval = true, since = "0.5.0")
static CompletionStage failedFuture(Throwable t) {
CompletableFuture future = new CompletableFuture<>();
future.completeExceptionally(t);
return future;
}
/**
* Applies a function on failure to produce another failure.
*
* @param upstream the upstream stage.
* @param mapper the mapper
* @param the type of emitted item
* @return the mapped completion stage.
*/
static CompletionStage applyExceptionally(CompletionStage upstream, Function mapper) {
Objects.requireNonNull(mapper, "The mapper cannot be null");
CompletableFuture future = new CompletableFuture<>();
upstream.whenComplete((res, failure) -> {
if (failure == null) {
future.complete(res);
} else {
Throwable throwable;
try {
throwable = Objects.requireNonNull(mapper.apply(failure));
} catch (Exception e) {
future.completeExceptionally(e);
return;
}
future.completeExceptionally(throwable);
}
});
return future;
}
/**
* Composes the given completion stage on failure.
*
* @param upstream the upstream stage
* @param mapper the mapper
* @param the type of emitted item
* @return the composed completion stage.
*/
static CompletionStage composeExceptionally(CompletionStage upstream,
Function> mapper) {
Objects.requireNonNull(mapper, "The mapper cannot be null");
CompletableFuture future = new CompletableFuture<>();
upstream.whenComplete((res, failure) -> {
if (failure == null) {
future.complete(res);
} else {
CompletionStage cs;
try {
cs = Objects.requireNonNull(mapper.apply(failure));
} catch (Exception e) {
future.completeExceptionally(e);
return;
}
cs.whenComplete((result, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else {
future.complete(result);
}
});
}
});
return future;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy