5.4 Deferred Callback Chaining

What sets deferred event objects apart from conventional callback implementations is their ability to support callback chaining. It is possible to attach multiple deferrable callback handlers to a single deferred event object such that when a callback is made the chained callback handlers are each invoked in turn. For the purposes of demonstrating this feature, the simple deferrable callback handler of Listing 5.5 is extended as shown in Listing 5.9.


\begin{listing}
% latex2html id marker 1216\begin{small}
\begin{verbatim}pub...
...end{verbatim}
\end{small}\caption{Simple Chained Callback Handler}
\end{listing}

Of particular interest in this version of the deferrable callback handler is that the onCallback method processes the input data and returns the modified version. In this case, it is simply a case of wrapping the string parameter with function-style parentheses. It is then possible to attach multiple deferrable callback handlers to the deferred event object as shown in Listing 5.10.


\begin{listing}
% latex2html id marker 1226\begin{small}
\begin{verbatim}......
...im}
\end{small}\caption{Creating Simple Deferrable Callback Chain}
\end{listing}

The example shown in Listing 5.10 also illustrates the use of the terminal parameter of the addDeferrable method. When adding the final deferrable in a chain the terminal flag must be set to true. This terminates the callback chain, making it ready for execution. For this reason, the final deferrable object in a callback chain is generally referred to as the terminal deferrable. Once a callback chain has been terminated, any attempt to add further deferrable callback objects will generate a runtime exception of type DeferredTerminatedException.


\begin{listing}
% latex2html id marker 1241\begin{small}
\begin{verbatim}INF...
...m}
\end{small}\caption{Output of Simple Deferrable Callback Chain}
\end{listing}

The full implementation of the chained callback example is present in the deferred examples package as DeferredChainExample1. Running the example code results in the console output shown in Listing 5.11. From this it is possible to see that processing the callback chain using the deferred event object is equivalent to making a set of nested function calls with the first callback method acting as the `innermost' function and the final callback method acting as the `outermost' function.