At the heart of backend as a service is data persistence. An easy way for developers to store data in the cloud and retrieve it from any connected device on any platform through a RESTful API. Combined with user management, social integration and custom server-side code, you’ve got a powerful platform at your finger tips.
One use case that traditionally is not supported by backend as a service is real-time data. For apps that want to implement chat, live auction, or graphs with realtime updates, developers often rely on “polling”. This involves having the client making requests to check for any updates and fetching them for display. The downside of polling is the resources required to continually ping a service. On mobile devices it contributes to draining the battery. Not a way to win friends and influence people.
The Publish/Subscribe model allows real-time streaming of data. Through technologies like WebSockets, Socket.IO and WebRTC developers can open and maintain connection to their apps and push messages from a server. PubNub was created to offer APIs that manage and scale to handle the millions of messages sent to devices through the Pub/Sub model.
Combining the StackMob API, for data persistence, and PubNub’s API for real-time messaging sounded like a good use case to demonstrate. I decide to build a proof of concept called VoiceMob. A simple voting app you could use for a live event. A user selects a question to see answer choices along with the current voting percentages. A pie chart and percentages update in real-time for anyone viewing the questions.
In StackMob Custom Code we chain together multiple actions. First, we increment the count for that answer. Next, we save the vote count to StackMob’s datastore. Lastly, we send a JSON array of answers and vote totals to PubNub’s API on a channel based on the question id. When a user views a question, they automatically subscribe to PubNub for any messages about that question. We installed PubNub marketplace module which created our account at PubNub and brought our PubNub API keys over to StackMob. Inside custom code, we can pull in our API keys at runtime.
Open the app VoiceMob in two separate browser windows, then vote to see both windows updated simultaneously.
All the code is available on GitHub.