Parse, acquired by Facebook a few months ago, has recently open-sourced a collection of low-level libraries for Android and iOS collectively called Bolts. According to Parse announcement, Bolts is the outcome of the joint Parse/Facebook effort to consolidate small, low-level utility classes that both companies had already developed on their own.
The first Bolts component that is available on GitHub is Tasks, aimed at handling asynchronous operations according to the JavaScript Promises model.
Promises attempt to solve a number of issues which are usually found when using callbacks to handle asynchronous operations, specifically the fact that trying to compose multiple serial or parallel asynchronous operations becomes quickly cumbersome due to nesting of asynchronous operations within callbacks.
To this aim, a Promise represents the result of a task that may or may not have completed, and which could eventually turn out into an error. Any asynchronous operation thus can immediately return a Promise on the result of its execution; the Promise can be accessed at any time, possibly blocking the caller if the async operation has not been completed yet.
Usually, though, a Promise is associated two callbacks that are to be called when the asynchronous task has been completed or has failed. What is peculiar of Promises is that callbacks are themselves encapsulated in a Promise, since they will be only executed at some point in the future, or not at all, depending on what happens with the original Promise.
Thanks to this mechanism, handling a sequence of asynchronous operations becomes straightforward, since Promises can be chained together to represent asynchronous operations and their callbacks, as shown in the picture above (source: Promises, Luke Smith.)
Another advantage of Promises lies with the way error propagates through a chain of Promises: since a Promise knows whether it has been fulfilled or not, it can propagate an error condition down along the Promises chain until an error handler is found, so you do not need to provide an error handler for each asynchronous operation in the chain.
Promises implementations are available in JavaScript, Scala, Clojure, and many other languages.
Parse claims that Tasks offers several advantages over both Android AsyncTask and iOS NSOperation, among them:
- Performing several tasks in a row will not create nested "pyramid" code as you would get when using only callbacks.
- Tasks are fully composable, allowing you to perform branching, parallelism, and complex error handling.
- You can arrange task-based code in the order that it executes, rather than having to split your logic across scattered callback functions.
Bolts components are completely unrelated to Parse or Facebook services and do not require having a Parse or Facebook developer account to be used.
More Bolts components are announced, but Parse has not released any details yet about them.