Being a good citizen – cleaning up after yourself

Okay, so I've told you the importance of calling .unsubscribe(), and you have taken my word for it at this point that if it is not called, resources won't be cleaned up. It is important to know about this mostly when you deal with streams that have a never-ending stream of data, such as scroll events, or in cases where you need to create your own Observables. I will now demonstrate a little bit of the internals of an Observable to make things clearer:

let stream$ = Observable.create( observer => {
let i = 0;
let interval = setInterval(() => {
observer.next(i++);
}, 2000)
})

let subscription = stream$.subscribe( data => console.log( data ));
setTimeout((
subscription.unsubscribe();
) =>, 3000)

This is an example of creating our own Observable. You think you are safe now just because you called .unsubscribe() like you were told? Wrong. The interval will keep on ticking because you didn't tell it stop. In panic, you close the browser tab and wish the Observable away—you are safe for now. The correct approach to this is to add a cleanup function, like so:

let stream$ = Observable.create( observer => {
let i = 0;
let interval = setInterval(() => {
observer.next(i++);
}, 2000);

return function cleanUp() {
clearInterval( interval );
}
})

let subscription = stream$.subscribe( data => console.log( data ));
setTimeout(() => subscription.unsubscribe(), 3000);

Upon calling subscription.unsubscribe(), it will call the cleanUp() function internally. Most of, if not all, factory methods out there used to create Observables will have their own cleanUp() function defined. It is important for you to know that should you venture down that rabbit hole of creating your own Observable, refer to this section, be a good citizen, and implement a cleanUp() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset