public interface ExecControl
There is a single instance for an entire application. It can therefore be constructor injected into services that scope several requests (i.e. execution contexts).
import ratpack.exec.ExecControl; import ratpack.exec.Promise; import ratpack.exec.Fulfillment; import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.handling.ChainAction; import ratpack.func.Action; import ratpack.func.Actions; import ratpack.test.UnitTest; import ratpack.test.handling.HandlingResult; public class Example { public static class AsyncUpperCaseService { private final ExecControl control; public AsyncUpperCaseService(ExecControl control) { this.control = control; } public Promise<String> toUpper(final String lower) { return control.promise(new Fulfillment<String>() { protected void execute() { success(lower.toUpperCase()); } }); } } public static class ServiceUsingHandler implements Handler { private final AsyncUpperCaseService service; public ServiceUsingHandler(AsyncUpperCaseService service) { this.service = service; } public void handle(final Context context) { service.toUpper("foo").then(new Action<String>() { public void execute(String string) { context.render(string); } }); } } public static void main(String[] args) { HandlingResult result = UnitTest.handle( new ChainAction() { protected void execute() { ExecControl control = getLaunchConfig().getExecController().getControl(); AsyncUpperCaseService service = new AsyncUpperCaseService(control); Handler handler = new ServiceUsingHandler(service); get(handler); } }, Actions.noop() ); assert result.rendered(String.class).equals("FOO"); } }
Note: when using the Guice integration, the exec control is made available for injection.
Modifier and Type | Method and Description |
---|---|
<T> Promise<T> |
blocking(Callable<T> blockingOperation)
Performs a blocking operation on a separate thread, returning a promise for its value.
|
<T> Promise<T> |
promise(Action<? super Fulfiller<T>> action)
Creates a promise for an asynchronously created value.
|
<T> Promise<T> blocking(Callable<T> blockingOperation)
T
- the type of value created by the operationblockingOperation
- the operation to perform that performs blocking IO<T> Promise<T> promise(Action<? super Fulfiller<T>> action)
This method can be used to integrate with APIs that produce values asynchronously.
The asynchronous API should be invoked during the execute method of the action given to this method.
The result of the asynchronous call is then given to the Fulfiller
that the action is given.
T
- the type of valueaction
- an action that invokes an asynchronous API, forwarding the result to the given fulfiller.Fulfiller
,
Fulfillment