Glossary:
Nirvana J2ME : Subscribing to a Channel
Once a Nirvana Channel (nChannel) has been found, you can subscribe to the channel, and receive Nirvana Events published on the channel.
Simple Subscription
This J2ME code snippet demonstrates how to subscribe to a channel:
long startEventID = 0;
nMIDlet myMIDlet = this;
nMIDlet.addSubscriber(myRatesChannel, myMIDlet, null, startEventID);
In order to keep the API library size compact, callback methods have been implemented in the nMIDlet base class, which is why we pass the midlet class itself as the event listener. The most important callback methods are:
- go(nObject consumeevent)
- disconnected(nObject session)
- reconnected(nObject session)
The go method is used by the server to deliver events to the client application. This is defined as an abstract method on nMIDlet so you need to implement it in your application.
The disconnected method is called whenever a subscriber loses its connection to the server, and the reconnected method is called whenever a subscriber re-establishes its connection back to the server. Note that the disconnected and reconnected methods do not need any implementation for automatic disconnection/reconnection to work, but you can override them to change the behavior.(The default is a System.out message)
At minimum, therefore, a subscriber must implement the following code:
public void go(nObject consumeevent) {
// process consumeevent nObject here
}
Subscription with a Filtering Selector
It is also possible to subscribe to a channel with a user-specified selector (a type of filter), ensuring that your client receives only events that match the selector. Selectors are SQL-like statements such as:
- name LIKE '%bank%' AND description IS NOT NULL
- (vol > 0.5 OR price = 0) AND delta < 1
This J2ME code snippet demonstrates how to subscribe to a channel and receive only events which have a key named "volatility" and a value greater than 0.5:
String myselector = "volatility > 0.5" nMIDlet.addSubscriber(myRatesChannel, myMIDlet, mySelector, startEventID);
Handling Received Events
As discussed above, you must implement a go method to handle any received events.
An example of such a handler function is given in the Nirvana Event page.
