In this lecture, we are going to learn how to push asynchronous values from our observables.
Up until now, our observable has been entirely synchronous.
We can improve this by logging some values in the observable.
We are going to push a new value with the next function.
Afterward, we are going to log a message before subscribing to the observer of all.
We will launch another message after the subscription.
Looking inside the console, we find our message is logged in the order they are written.
Typically, most observables you'll be working with are asynchronous at this point.
We've got a good grasp of how observables work.
We're going to start taking things a step further by working with asynchronous values.
It's much more practical to use our SJS in this manner.
Let's modify our observable.
We will start with a simple example inside the function we will call the set interval function with
a duration of 1000 milliseconds.
Inside the interval, we will call the next function with a message.
We're logging a message every seconds, the observer is constantly watching the observable for new values.
As you can see, the council is continuously logging values.
There are no limits as to how many values we can push.
Our interval or run infinitely that much is easy to understand.
However, we have a bigger problem.
What if we want to complete the observable?
Does that mean the interval will stop running?
Not necessarily after calling the next function in the interval.
Let's call the complete function on the subscriber object.
In the log, the observer will stop logging values despite the observer completing we have a memory
leak.
The interval is still running inside the interval.
We will log a message.
After a few seconds, the council will continue to log messages completing an observable does not mean
the contents of an observable have been cleared.
Memory is still being allocated for the interval.
We should free this memory if the observable is no longer running.
This is important to understand.
We are responsible for cleaning the memory in an observable.
Otherwise, we may experience sluggish performance from memory leaks.
We should clear the interval after completing the observable.
We can return a function from an observable to handle cleaning up asynchronous operations.
First, let's store the I.D. returned from the set interval function.
Next, we can clear the interval with the clear interval function.
After updating our file, the logs have stopped once the observable completes, the returned function
will be invoked, which will clear the interval.
This behavior can be tricky to deal with.
Observables offer a lot of benefits.
But we should be aware of situations like this.
We will look at an alternative situation in the next lecture.