Observables vs Promises
Both Promises and Observables provide us with abstraction that helps us to deal with the asynchronous nature of our Applications. However, there are important differences between the two:
As seen in the example above, Observables can define both the setup and teardown aspects of asynchronous behavior.
Observables are cancellable.
Moreover, Observables can be retried, using one of the retry operators provided by the API, such as retry and retryWhen. On the other hand, Promises require the caller to have an access to the original function, which returned the Promise in order to have a retry capability.
Observable HTTP Events
A common operation in any Web Application is getting or posting the data to a Server. Angular Applications do this with Http library, which previously used Promises to operate in an asynchronous manner. The updated Http library now incorporates Observables to trigger the events and getting new data.
Observables Array Operations
In addition to simply iterating over an asynchronous collection, we can perform other operations such as filter or map and many more as defined in the RxJS API. This is what bridges an Observable with the iterable pattern and lets us conceptualize them as collections.
Here are two really useful array operations - map and filter. What exactly do these do?
map will create a new array with the results of calling a provided function on every element in this array. In the example given below, we used it to create a new result set by iterating through each item and appending the word ‘Mr’ abbreviation in front of every employee's name.
filter will create a new array with all the elements that pass the test implemented by a provided function. Here, we have used it to create a new result set by excluding any user whose salary is below 20000. Now, when our subscribe callback gets invoked, the data it receives will be a list of JSON objects, whose id properties are greater than or equal to 20000 salary.
Note the chaining function style and the optional static typing, which comes with TypeScript, which we used in this example. Most importantly functions like filter return an Observable, as in Observables we get other Observables, which are similar to Promises. In order to use map and filter in a chaining sequence, we have flattened the results of our Observable, using flatMap. Since filter accepts an Observable and not an array, we have to convert our array of JSON objects from data.json() to an Observablestream. This is done with flatMap
To demonstrate the above concept, create the files given below with the code.