Perform an Action on Completion with RxJS Observables

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet

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.

[00:00] 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.

[00:23] 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.

[00:43] 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.

[01:06] 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.

[01:20] 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.

[01:36] 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.