T
- the type of value that is promisedpublic final class Promised<T> extends java.lang.Object implements Downstream<T>
A “promised” can be used by the producer of a value to notify an interested parties when the value becomes available.
Zero or more promises can be created for the promised value via the promise()
method.
Promised
extends Downstream
, which represents the write side of async values.
To supply the promised value, simply call exactly one of the methods inherited from Downstream
.
A “promised” can have zero or more listeners, but can only be fulfilled once.
All of the methods inherited from Downstream
will throw an Promised.AlreadySuppliedException
if a value, error or completion have already been signalled for this topic.
import ratpack.test.exec.ExecHarness;
import ratpack.exec.Execution;
import ratpack.exec.util.Promised;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertEquals;
public class Example {
public static void main(String... args) throws Exception {
AtomicReference<Long> ref = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
ExecHarness.runSingle(e -> {
Promised<Long> topic = new Promised<>();
// create a listener
Execution.fork().start(e1 ->
topic.promise().then(v -> {
ref.set(v);
latch.countDown();
})
);
// fulfill the topic, notifying listeners
topic.success(1l);
});
latch.await();
assertEquals(1l, ref.get().longValue());
}
}
Modifier and Type | Class and Description |
---|---|
static class |
Promised.AlreadySuppliedException
Thrown if an attempt is made to supply the value/result after it has already been supplied.
|
Constructor and Description |
---|
Promised() |
Modifier and Type | Method and Description |
---|---|
void |
accept(ExecResult<? extends T> result)
Signals this downstream, based on the given result.
|
void |
complete()
Signals that the upstream will not be providing a value, as it has terminated.
|
void |
error(java.lang.Throwable throwable)
Signals the unsuccessful production of the upstream value.
|
Promise<T> |
promise()
Creates a new promise for the eventual value.
|
void |
success(T value)
Signals the successful production of the upstream value.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
accept, accept, accept, completionHandler, onComplete, onError, onSuccess
public Promise<T> promise()
public void success(T value)
success
in interface Downstream<T>
value
- the upstream valuepublic void error(java.lang.Throwable throwable)
error
in interface Downstream<T>
throwable
- what went wrongpublic void complete()
complete
in interface Downstream<T>
public void accept(ExecResult<? extends T> result)
accept
in interface Downstream<T>
result
- the result to signal