Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Perform an Action on Completion with RxJS Observables


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.