This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Observables can complete

1:48 RxJS lesson by

The Observer object has the functions next() and error(). In this lesson we will see the other (and last) function available on observers, complete(), and its purpose.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

The Observer object has the functions next() and error(). In this lesson we will see the other (and last) function available on observers, complete(), and its purpose.

So far, we've seen that observers are the consumers of values that observable produces. Observers seem to have at least two functions attached to them. They have next to get values. They have error to get an exception. What else does this observer object include? It also has complete, which takes no value or error. It has zero arguments.

Observer.complete allows a producer, this observable, to tell its consumers that it has finished. It won't deliver any values anymore. In the subscribe here, we can add a third handler, the complete handler, which also takes no arguments. Here, we can detect when the observable ended.

When you run this, you see hello, 42, 100, and 200, and done, because after 200 we told observable that we're done. That's why this delivery of a value here didn't happen, because we have completed already. I could have also put the complete here so that we're only going to be done after 300 is delivered.

Completion is an important concept, as we will see later on. Imagine if you want to concatenate two observables. You can only do that if the first one ends. Then you know that the second observable takes over after that.

Completion is also important in other ways. For instance, let's say that observer is only interested in the last value that observable produced. This last can only be determined if there is a way to know that the observable has finished and won't deliver any values anymore.

In conclusion, that's all an observable can do. It can deliver values, pushing them to observers. It can deliver errors. It can deliver a completion notification.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?