Events are deepstreamHub's implementation of the "publish/subscribe" or "observer" pattern. If you're familiar with e.g. JavaScript event-emitters or Java events, you know how they work. Zero or more interested clients subscribe to an event (sometimes also called a "topic", "channel" or "namespace"), and zero or more other clients publish to it.
The emphasis on "zero or more" underlines one of the main characteristics of pub/sub: Publishers and subscribers are completely decoupled. It's a bit like a newspaper - journalists write articles assuming - but not knowing that they will be read. Readers open the sports section expecting, but not knowing that something will be written on it.
Pub/Sub and its limitations
Due to its simplicity and versatility, pub/sub is the most widely adopted pattern for realtime systems with many hosted (e.g. Pusher, PubNub) or self-hosted server-to-client (e.g. socket.io, SocketCluster) or server-to-server (e.g. Redis, Kafka) solutions available.
However, pub/sub is purely a lightweight way of messaging that doesn't have any concept of persistence or state. It's therefore often used to notify clients of changes which in turn trigger a separate HTTP request to retrieve the actual data.
This comes with significant overhead and is increasingly abandoned in favour of "data-sync", an approach where the actual data is distributed and kept in sync across all subscribed clients. Data-sync is the mechanism behind deepstreamHub's realtime-datastore and can be used in the form of records and lists.
Having said that, pub/sub vs data-sync doesn't need to be an either/or decision. Both complement each other well and can be used together for many use cases.
How to use events
Subscription to events can be established with client.event.subscribe()
and removed with client.event.unsubscribe()
.
// Client A
function eventCallback(data) {
//callback for incoming events
}
//Subscribing to an event
client.event.subscribe('news/sports', eventCallback)
//Removing specific callback to the event
client.event.unsubscribe('news/sports', eventCallback)
//Removing all subscriptions to the event
client.event.unsubscribe('news/sports')
Events can be published using client.event.emit(eventName, data)
. It is possible to send any kind of serializable data along with the event, e.g. Strings, JSON objects, Numbers, Booleans etc.
// Client B
client.event.emit('news/sports', 'something about football is happening')
Video Demo
If you would like to learn more about events, have a look at this video tutorial with Yasser Fadl, explaining more in detail about Pub/Sub in deepstreamHub.