4.4 Subscribing and Unsubscribing

The signal event API provides a mechanism for signalable objects to subscribe to a given signal in order to receive signal event notifications and also to unsubscribe from the signal when such notifications are no longer required. This makes the signal mechanism ideally suited for implementing the Publisher-Subscriber pattern[4].

In the Publisher-Subscriber pattern one component acts as a data source (the publisher) and one or more components act as data consumers (the subscribers). The publisher provides a number of data accessor methods and some mechanism for notifying its subscribers of changes to that data. In the case of the Reaction framework the notification mechanism is the signal event. An example interface for a publisher component is shown in Listing 4.7.


\begin{listing}
% latex2html id marker 923\begin{small}\begin{verbatim}publi...
...);
}\end{verbatim} \end{small}\caption{Simple Publisher Interface}
\end{listing}

This publisher interface is a minimal implementation with a single notification signal and a single data accessor method. The data accessor converts the internal data to a string and the change notification signal is triggered whenever the internal data changes. A subscriber may then subscribe to the change notification signal so that it is informed whenever the data value changes. This is illustrated in the setup method of the simple subscriber implementation shown in Listing 4.8.


\begin{listing}
% latex2html id marker 933\begin{small}\begin{verbatim}publi...
...nd{verbatim} \end{small}\caption{Simple Subscriber Implementation}
\end{listing}

Once subscribed, signal notifications which are received via the onSignal method are used as a trigger for the subscriber to read back the latest publisher data via the publisher's accessor method. This will continue until the subscriber component is unsubscribed from the publisher, as illustrated by the teardown method in the example. Once unsubscribed, no further change notifications will be received unless the subscriber re-subscribes to the publisher service. A full implementation of this example is provided in the signal examples package as SignalSubscribeExample.

In the example implementation of the publisher service, it is worth commenting on the use of the signal data parameter. The example shows the data parameter being used as a sequence number which is incremented each time the update signal is triggered, as demonstrated in Listing 4.9. Use of this idiom is considered good practise in that it provides a way for subscribers to synchronise state with the publisher if required.


\begin{listing}
% latex2html id marker 946\begin{small}\begin{verbatim}publi...
...nd{small}\caption{Passing Sequence Number in Update Notifications}
\end{listing}