The starting point for working with deferred event objects is to consider an example of a long running task which will issue callbacks using the deferred event mechanism. One such example is given in Listing 5.4, which uses a timer as a proxy for processing or I/O delays.
In this example, the long running task is initiated by making a call to the runTask method, which returns a reference to a new deferred event object. The onTick timer callback signifies the completion of the task, at which point the deferred callback is triggered - passing the `result' of the operation as the callback parameter. A Java generic type specifier is used to identify the callback parameter type, which in this case is set to a standard Java String.
To accompany the simple timer-based task, a callback handler is required in order to process the generated result. This can take the form of a simple deferrable object which implements the Deferrable interface as shown in Listing 5.5.
The onCallback callback handler implemented in Listing 5.5 simply prints out the deferred result of the long running task and then stops the reactor in order to terminate the test. The onErrback error handler is not used in this context but must be provided in order to fully implement the Deferrable interface. Note that Java generic type specifiers are used to parameterise the input and output types of the callback functions. In this case the callbacks expect an input parameter of type String and will generate an output which is also of type String.
Given these implementations of the simple long running task and simple deferrable callback handler, the long running task may be executed using just the two lines of code shown in Listing 5.6. The full implementation is provided in the deferred examples package as DeferredEventExample1.
The first of the two lines creates the new long running task and starts it running, accepting the deferred event object which is returned. The second of the two lines attaches the simple callback handler to the deferred event object so that the callback can be executed on completion of the long running task. As part of attaching the callback handler, the terminal parameter is set to true which indicates that no further callback handlers will be attached to the deferred event object. The use of the terminal parameter will be explored in more detail when callback chaining is introduced in Section 5.4.