
com.simplaex.bedrock.Promise Maven / Gradle / Ivy
package com.simplaex.bedrock;
import lombok.Getter;
import javax.annotation.Nonnull;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
public class Promise implements Callback {
public enum State {
PENDING,
FULFILLED,
FAILED
}
@Nonnull
@Getter
private volatile State state;
private volatile Object result;
private Promise(@Nonnull final State state, final Object result) {
this.state = state;
this.result = result;
}
@Nonnull
public static Promise promise() {
return new Promise<>(State.PENDING, null);
}
@Nonnull
public static Promise fulfilled(final T value) {
return new FulfilledPromise<>(value);
}
@Nonnull
public static Promise failed(final Throwable value) {
return new FailedPromise<>(value);
}
private static class FulfilledPromise extends Promise {
private FulfilledPromise(final T result) {
super(State.FULFILLED, result);
}
@Override
public void fulfill(final T result) {
throw new IllegalStateException("Already fulfilled (" + getState() + ").");
}
@Override
public void fail(final Throwable result) {
throw new IllegalStateException("Already fulfilled (" + getState() + ").");
}
@Override
@Nonnull
public Promise onComplete(@Nonnull final Callback callback) {
Try.unfailable(() -> callback.call(null, getValue()));
return this;
}
}
private static class FailedPromise extends Promise {
private FailedPromise(final Throwable exc) {
super(State.FAILED, exc);
}
@Override
public void fulfill(final T result) {
throw new IllegalStateException("Already fulfilled (" + getState() + ").");
}
@Override
public void fail(final Throwable result) {
throw new IllegalStateException("Already fulfilled (" + getState() + ").");
}
@Override
@Nonnull
public Promise onComplete(@Nonnull final Callback callback) {
Try.unfailable(() -> callback.call(getException(), null));
return this;
}
}
private abstract static class UntypedPromise extends Promise
© 2015 - 2025 Weber Informatics LLC | Privacy Policy