In this lecture, we are going to unsubscribe from an observable from the observer.
Previously, we saw how to run a function when an observable completes, it's considered good practice
to complete an observable whenever we don't need it anymore.
On the other hand, I wonder if we want an observable to run forever.
Different parts of our apps may need to subscribe to the same observable.
If an observer doesn't need to listen to data from an observable anymore, we should unsubscribe from
the observable without interrupting other observers.
It's completely possible for a single observer to unsubscribe from an observable.
This behavior allows for other observers to continue receiving data uninterrupted in our file.
We are going to remove the complete function.
The observable should run forever.
Instead of completing the observable, we will unsubscribe from the observable with our observer.
Let's hover our mouse over the subscribed function, according to the editor.
These subscribed functional returns an object called subscription.
In the resource section of this lecture, I provide a link to the subscription object documentation
page.
The description says the following a subscription is an object that represents a disposable resource.
Usually, the execution of an observable a subscription has one important method unsubscribe that takes
no argument and just disposes the resource held by the subscription.
The subscription object doesn't serve much of a purpose besides providing a function for unsubscribing
from an observable.
It's precisely the function we're looking for.
Let's go back to the editor.
We should store the subscription object.
We will store the object in a variable called subscription.
Below the Subscribe function, we will call the set timeout function with a duration of 4000 milliseconds.
Inside the callback function, we will call the unsubscribe function on the subscription object.
In the console, the message is we'll continue to get launched after four seconds, they will cease
appearing in the log.
Not only has the subscription been cancelled, but the interval has been released.
The function were returning from the observable will be executed when the observable completes or an
observer unsubscribe.
In either scenario, we are given the opportunity to release memory.
You may have noticed it already, but the complete function from our observer never runs.
Hence, we can assume the observable has not completed.
It's exactly what we wanted in the console.
The message from the complete function never appears.
Other observers can continue to listen for new data from the observable.
Our SJS gives us flexibility with managing observables and observers before moving on.
I want to clean up the code in our file.
Let's remove the console statements before and after the subscription.
In the following lecture, we're going to start discussing operators for helping us write observables.