RxJS: ordinary unsubscribe

Wojciech Trawiński
JavaScript everyday
2 min readAug 20, 2018

Description

In my previous post I outlined the main differences between a Promise and an Observable. A friend of mine pointed out that there is a one missing point in the article, namely that an Observable can be cancelled. In today’s post I will explain what the cancellation means, especially in terms of http requests.

Goal

The main aim of today’s article is to understand what can be accomplished with the aid of unsubscribe method.

Time interval

Let’s start with a basic example in which the next value is provided to an Observable with the aid of setInterval method.

After 2 seconds, the unsubscribe method is called on a Subscription instance. As a consequence:

  • no further notifications will be provided to the stream,
  • the function returned from Observable constructor’s callback will be executed,
  • the interval will be cleared.

As a result, you will see two pairs (internal and the one from subscribe callback) of console.log.

However, if you don’t return the function to be executed upon unsubscribe call, the internal console.log will appear every 1s even though you have unsubscribed.

As you can see, there is no magic happening under the hood within the unsubscribe method. It’s just a way to get rid of further notifications in the resulting stream. The method doesn’t automatically free resources. It just gives you opportunity to the the right clean-up within the returned callback function.

HTTP request

Without using a third-party library you can make an http call either using XHR object or the fetch method. The former approach gives an opportunity to cancel a pending request by calling abort method. So it’s not about using an Observable to make an http request, but it’s all about its underlying implementation.

In the above example, I use an Observable to make an http request. However, due to fetch API usage, calling unsubscribe method doesn’t cancel the pending request. The stream won’t receive a value, but the console.log within the second then will be executed. In order to cancel the request, you need to both use an Observable, which gives you a chance to register a callback function that will be executed upon unsubscription, and the XHR which has the abort method.

In the above example, the pending request will be successfully cancelled.

Remarks

Calling unsubscribe on a Subscription instance results in:

  • getting rid of further notifications in the stream,
  • invoking the provided callback function, which is an appropriate place to do the clean-up and free resources.

Unsubscribe just executes the optional callback function. It won’t do the clean-up for a developer.

--

--