This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Creation operator: create()

3:03 RxJS lesson by

We have been using Observable.create() a lot in previous lessons, so let's take a closer look how does it work.

Get the Code Now
click to level up comment guidelines


We have been using Observable.create() a lot in previous lessons, so let's take a closer look how does it work.

We have been using observable.create a lot in previous lessons, so let's take a closer look at how does that work. Observable.create is actually the same as calling the constructor of the observable type. This here still behaves the same.

The constructor takes just one argument, which is a function. That function takes one argument, that observer. Then you're supposed to call and error or complete, like we saw in previous lessons.

If we would give a name for this function, what would that be? Here's a good suggestion -- subscribe. If we paste that function back here, give it a name, that's what's going to be passed here as the argument to the constructor. If you think there's some similarity between the function that we're calling and the function that we created, that's a correct guess.

Here's an alternative way of writing this. Instead of giving three functions as arguments, we can give an object that has three fields -- next, error, and complete. Each of these are functions. This takes a x value, and then we will say console.log next x. The error is also a function. The complete is also a function.

If we will give a name for this object actually, so we can extract this, give a name to it, let's say observer, it's an object. That's what we're going to pass down here. Now it's starting to make sense, how does Rx observables work. This function here is basically that function. We're calling that function given this object that has these three callbacks.

If you want to see if it would work without all this RX machinery, this is really JavaScript. We don't have any more RX. We have a function subscribe that takes an object observer with some callbacks, and it's going to call those callbacks. As you can see, this all still works.

Of course, it's useful to have the observable type because then it has all those nice operators that we saw and that we are also seeing new operators coming next. If you paid attention, then you're going to remember that in the subscribe, we had previously three functions here as argument. Instead of an object, as we have now, we had just these three functions.

Also, the observable type, it converts these three functions into an observer object. Before it calls this, it will actually take these three functions and put labels in front of them like that, to create the observer object. It's normalizing it.

That's in a nutshell what observable.create was. It's the same thing as the constructor. This is how the constructor works in a nutshell.

Joel's Head
Why are we asking?