So far, when writing these subscribe functions, we haven't returned anything. It is possible return an unsubscribe function from a subscribe function. In this lesson we will see how to allow observers to subscribe and unsubscribe from an Observable.
So far when writing the subscribe functions which are 'past' and 'observable' constructor, we haven't returned anything. But it's possible to return an unsubscribe function from this. Here's how it's useful.
Let's say inside this function I want to set an interval to run this every one second. Every one second, I'm going to deliver a value to the observer. I'm going to say 'hi,' for instance. Now when we run his, we see the string 'hi' being delivered every one second.
Now, suppose that after four and half seconds, I don't want to receive these 'hi' values anymore. Let's say the observer is done receiving values. It doesn't want to get values. Since we're subscribing, we should also have a way of unsubscribing. That's where this return function, 'unsubscribe', comes in.
Now we have this unsubscribe function that we can call anywhere here. Let's say, for instance, here. The setInterval will return to us this ID number for the interval that was registered. Then you can stop that by calling this API clearInterval with the ID. We call that precisely here inside our 'unsubscribe'.
Basically, when I call 'unsubscribe', it will clear the interval. I can do that after four and a half seconds. When we run this, we should see just four values. Then it should unsubscribe. It did. That's what returning this function, 'unsubscribe', is. It's a way of being able to stop receiving values because 'subscribe is saying', "Give me values."
The subscription is just an object which has the 'unsubscribe' function. It's almost the same thing, but just a slightly different API. This also works.
The idea is that you are able to dispose from resources that you are using here so that this wouldn't leak, because if the observer is not interested in those values anymore, then we can stop everything that was running.