In this section, we will continue from the last section. We will begin this by discussing about observables API. You can check more about observables at http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html.
First thing, I am going to create a data source using Observable as shown below in snapshot. You can also see that there are number of APIs available from Observable.
Here, I am using from API from the different APIs available as shown below.
Below is the completed snippet for observable.
Let’s walk-through this code. Usually the classic way of doing this by creating class. Here, my observer class has three things next, error and complete. And, once observer gets created, then we need to subscribe the same by creating an instance in the data source. And, once you refresh the page again, then you can see that in console window that my observer did produce the value from 0 to 9 and finally the complete message.
However class is the most formal way of implementing observable pattern. However, you can implement observer interface as well in this like shown below in the snippet. This is the generic way of using this Observer pattern. You may also notice, first I imported that interface then I have implemented in the class and then instantiated the class. Here, I have also passed number as my valid argument.
In this case, it will stick to the number only. Also, if I make any mistake while implementing interface, then it will highlight quickly then and there as shown below.
This is the one way of using that observable. Although, this was not asynchronous but at least you understand the gist of this pattern. In the next section, we will extend the same example with more APIs. Till then stay tuned and Happy Coding.