Observable and Observer

Having defined all the concepts we need to know initially, it is now time to put it all in context to further our understanding. Let's start off by defining an Observable and work ourselves into each previously mentioned concept. An Observable can be created with the following code:

let stream$ = Rx.Observable.create(observer => observer.next(1));

This is the least amount of code needed to create an Observable. At this point nothing is written to the screen because we need to subscribe to the stream. Let's add a Subscriber to our Observable. We do that by calling the method subscribe() on our stream instance:

let stream$ = Rx.Observable.create(observer => observer.next(1));
stream$.subscribe(data => console.log('data',data) ) // write data, 1 to the console

Looking at this code, we see that the Observable calls the method create(), which in turn creates an instance of an Observable. What is interesting is how the create() method takes a function as a parameter; a function that itself takes an Observer instance. So, we have an API that looks like this: Observer.create(fn(observerInstance)). What happens inside said function is that we call observer.next(1).  At a higher level, we have an Observable that is created by us using a factory function create(). The create function takes a function as a parameter which defines the behavior of the Observable. Our Observable behavior in this case is very simple, which is to emit the value 1. When we call observer.next(1), we emit data. To get hold of what is emitted, we need to call the subscribe() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.146.77