<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jurek Wozniak on Medium]]></title>
        <description><![CDATA[Stories by Jurek Wozniak on Medium]]></description>
        <link>https://medium.com/@jaywoz?source=rss-d2fd148b034------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nv9H_Lb9ys4EnAHGjfwUHQ.jpeg</url>
            <title>Stories by Jurek Wozniak on Medium</title>
            <link>https://medium.com/@jaywoz?source=rss-d2fd148b034------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:02:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaywoz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[To unsubscribe, or not to unsubscribe, that is the question. — Subscriptions in RxJS]]></title>
            <link>https://jaywoz.medium.com/rxjs-when-to-unsubscribe-c6f39b8b95b7?source=rss-d2fd148b034------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6f39b8b95b7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[observables]]></category>
            <dc:creator><![CDATA[Jurek Wozniak]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 21:40:47 GMT</pubDate>
            <atom:updated>2024-08-19T08:04:05.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>To unsubscribe, or not to unsubscribe, that is the question. — Subscriptions in RxJS</h3><p>Some say RxJS is all about <strong>Observables</strong>. While I can agree with that to some extent, I will be a bit more controversial and say that RxJS is all about <strong>Subscriptions</strong>. Let me justify this. An Observable on its own does not do anything. It just<strong> stores the logic</strong> how will the notifications be generated once it is executed. A Subscription is what <strong>executes</strong> the code placed inside of an Observable and puts it into action. So the Subscriptions are what actually makes things <strong>happen</strong>. With that comes a great responsibility — as some of the Observables can emit the values in an endless open-ended fashion, we need to make sure that the Subscriptions are <strong>closed</strong> at some point, so a proper cancellation, clean up and disposing of the resources can happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XKCsPbH-Atxg262x" /><figcaption>Photo by <a href="https://unsplash.com/@dimhou?utm_source=medium&amp;utm_medium=referral">Dim Hou</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Subscription can end in <strong>a few ways</strong>. One of the ways is to call .unsubscribe() on the Subscription we want to close. The topic when and whether to <strong>unsubscribe</strong> can get quite confusing. In this article, I will try to demystify the topic of the Subscription.</p><h3>What happens if I do not unsubscribe?</h3><p>RxJS is all about <strong>Subscriptions</strong>. They execute the <strong>Observables</strong>. Leaving active <strong>unused</strong> Subscriptions, in the best case scenario, can lead to minor <strong>memory leaks</strong>. In worse scenarios and when your app runs for longer, you will experience memory and/or <strong>performance issues</strong>. In the worst case, your app will act strangely and might even <strong>crash</strong>.</p><p>We need to make sure that the Subscriptions <strong>end</strong> at some point, and they are not hanging in the memory endlessly. To write decent and <strong>reliable</strong> RxJS code it is essential to understand how <strong>Subscriptions</strong> work and when to <strong>unsubscribe</strong>.</p><p>You do <strong>not always</strong> have to unsubscribe. In fact it is best to write your code in a way the Subscriptions are mostly handled for you — we will get to this later.</p><p>In this article you will learn how the Subscriptions work to understand what is the <strong>Subscription’s lifecycle</strong> and how to find out whether you need to unsubscribe from the Observables you have in your code or not.</p><h3>What is a Subscription?</h3><p>Before we get into the details, we need to clarify what a <strong>Subscription</strong> actually is. Very often it is understood as something much more complicated than it actually is.</p><p>To cut the long story short, a Subscription is <strong>like a call</strong> to the function with the logic placed inside of the Observable to which we are subscribing.</p><p>To better understand what I mean by the above, let us see what the <strong>Observable</strong> actually is.</p><h4>What an Observable is?</h4><p>An Observable on its own <strong>does not</strong> do anything. It just describes the <strong>logic</strong>, how the values <strong>will be generated</strong> when this logic gets executed. In other words, an Observable is just an object with some rules and guarantees regarding its capabilites and interface. It is focused around a <strong>function</strong> containing the <strong>logic</strong> of the Observable. This function is passed to the new Observable constructor as an argument and <strong>describes</strong> the way the <strong>notifications</strong> will be emitted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5645e5e9d4730919d3598a221fd31651/href">https://medium.com/media/5645e5e9d4730919d3598a221fd31651/href</a></iframe><p>Most often, <strong>instead</strong> of using the new Observable constructor — as seen above, you will use some <strong>helper functions</strong> creating Observables, such as of(), from(), timer(), interval() and many many others, however each of these functions will <strong>actually</strong> use the new Observable constructor inside and <strong>return</strong> the resulting Observable. What is important to know at this point is that each Observable has this <strong>function</strong> embedded inside, and this function describes the <strong>logic</strong> of the Observable — how the <strong>notifications</strong> will be generated.</p><p>Each time you call .subscribe(...) on the Observable, this internal <strong>function</strong> in the Observable is <strong>called</strong>. So, each Subscription is a <strong>separate execution</strong> of the Observable’s logic.</p><p>Try this out in this coding sandbox below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-subscription-multiple-subs%3Fembed%3D1%26file%3Dindex.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-subscription-multiple-subs%3Ffile%3Dindex.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Fsocial_editor-1e53e71ce7e2963fcef1b44837c4570c3fb10c8cb64b194a6eafa4e145d10edc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4edbe52d34d98e70ea80377550d71a3f/href">https://medium.com/media/4edbe52d34d98e70ea80377550d71a3f/href</a></iframe><p>In the above example you can see that there is a console.log inside of the function passed as the <strong>logic</strong> of the Observable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18cbe16f18a03f7257315973cc184171/href">https://medium.com/media/18cbe16f18a03f7257315973cc184171/href</a></iframe><p>Then each time we would make a new Subscription to this Observable by calling observable$.subscribe(), a <strong>separate execution</strong> of the Observable will happen. So if we would subscribe to this Observable <strong>three times</strong>, we would <strong>see</strong> this console.log three times as the Observable’s <strong>logic</strong> will be <strong>executed</strong> three times — independently for each Subscription. This is how RxJS is designed. Each time you <strong>subscribe</strong> to an Observable, the <strong>logic</strong> inside of the Observable gets <strong>executed</strong>. That is a very important thing to know to understand Subscriptions well — the Subscriptions are not something really complex and magical. In essence they are just a way to <strong>call the logic</strong> inside of the Observable.</p><h4>What are the Subscriptions for?</h4><p>To cut the long story short, the main thing is that <strong>Subscriptions</strong> enable us to <strong>cancel</strong> the execution of an Observable. This is not particulary useful in cases like the previously mentioned, where the Observable instantly emitted two values and then completed. Let us have a look at a few examples, where this might be <strong>useful</strong>:</p><ul><li><strong>DOM event emitters</strong> — a very popular source of Observables which can be created by using the fromEvent() function; imagine that we enter some view in our app and start listening to the ‘click’ event of some button, then get notified each time such event gets dispatched, and finally, when we are no longer interested in these events, we might want to stop receiving them,</li><li><strong>WebSockets </strong>— we might want to start the connection and then if we are no longer interested in the data, we might want to stop receiving the values and end the connection,</li><li><strong>interval generators </strong>— we might have an Observable endlessly generating values every few seconds, if we would not have the option to cancel such timer, we would endlessly get triggered with updates coming from this Observable,</li><li>…tons of others!</li></ul><p>As you can see there are many cases in which we have <strong>‘subscribable’</strong> sources, to which we want to <strong>connect</strong> and <strong>disconnect</strong>. That is probably why the Observable’s execution is called a <strong>Subscription</strong>. As RxJS can do a lot of things it was difficult to find a better abstraction of what it does and how to name it.</p><p><strong><em>Fun fact:</em></strong><em> Subscription was previously called Disposable, so it was even more confusing than now.</em></p><p>As a side note, if we would name things differently — <strong>subscribing </strong>is <strong>executing</strong> the logic inside of the Observable and <strong>unsubscribing </strong>is a way to <strong>cancel</strong> these executions. So when we call .unsubscribe() on one of our Subscriptions we are actually <strong>cancelling</strong> this <strong>particular execution</strong> of the Observable.</p><h3>How can a Subscription end?</h3><p>You create a new Subscription by calling the .subscribe(...) method on the Observable. This <strong>executes</strong> the Observable’s <strong>logic</strong>.</p><p>Then, as long as the Subscription <strong>works</strong>, the Observable can <strong>emit values</strong> by emitting <strong>any</strong> (0…N) number of the next <strong>notifications</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a98ca659172875d0b8909ebba40620a/href">https://medium.com/media/0a98ca659172875d0b8909ebba40620a/href</a></iframe><p>This Subscription will be present in the memory <strong>until</strong> it gets closed.</p><p>There are <strong>three ways</strong> in which a Subscription can <strong>end</strong>:</p><ul><li>The Observable can emit a <strong>complete</strong> notification.</li><li>The Observable can emit an <strong>error</strong> notification.</li><li>Your code can call <strong>.unsubscribe()</strong> on the Subscription.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/468f129afc5aa1df4de27a95d3018eba/href">https://medium.com/media/468f129afc5aa1df4de27a95d3018eba/href</a></iframe><h3>So, when do I need to unsubscribe?</h3><p>As you could see there are <strong>three ways</strong> in which the Subscription can <strong>end</strong>, or in other words, get <strong>closed</strong>. Two are determined by the Observable’s logic — emitting a <strong>complete</strong> or <strong>error</strong> notification. And one is in our hands — <strong>unsubscribing</strong>.</p><p>Most often you will want your Subscriptions to happen when you <strong>open</strong> some <strong>view</strong> or some <strong>component</strong> would show up on screen. Then, your Subscriptions would react to various events, perform API calls, etc. Finally, when you <strong>close</strong> that view or <strong>hide</strong> the component you would want to make sure that these Subscriptions are <strong>closed</strong> and do not cause further reactions and/or hang in the memory.</p><p>In short, every Subscription <strong>should end</strong> somehow, when it is no longer needed — either by receiving a complete or error notification or by unsubscribing. If you make sure that this happens for all of your Subscriptions, you are good and your app should not have <strong>memory leaks</strong> and <strong>issues</strong> related to leaving open Subscriptions.</p><blockquote><strong>Note: </strong>An exception from the above rule is that if you want to have some Subscriptions running all the time while your app runs. You can leave them going all the time without unsubscribing, as that is what you want in these cases.</blockquote><h4>Complete or Error notification</h4><p>The complete notification is used to signal that the Observable has <strong>done</strong> its job and <strong>will not</strong> emit any more values. The error notification is used to inform that something <strong>failed</strong> and the Observable is <strong>not able</strong> to emit further values.</p><p>In both cases, these notifications mean that the Observable will not emit any further values (next notifications) after emiting either of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43229a5d6adf1430a9118a2c63f0a096/href">https://medium.com/media/43229a5d6adf1430a9118a2c63f0a096/href</a></iframe><p>After the Observable emits either of these notification, the Subscription will end immediately, so the Observable will not emit any further values (next notifications) and we <strong>do not need</strong> to <strong>unsubscribe</strong>.</p><h4>Unsubscribing</h4><p>There are some Observables which <strong>never</strong> complete or error. In such case, if we want to <strong>stop</strong> the Subscription and, in other words, the execution of our Observable, we can <strong>unsubscribe</strong>. Calling the .unsubscribe() method on the Subscription will also end the Subscription, the same way as the complete and error notifications emitted by the Observable did.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-subscription-unsubscribe%3Fdevtoolsheight%3D33%26embed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-subscription-unsubscribe%3Fdevtoolsheight%3D33%26embed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Fsocial_editor-1e53e71ce7e2963fcef1b44837c4570c3fb10c8cb64b194a6eafa4e145d10edc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/abe07c6c27a316a3e0e1cc7de7f28b51/href">https://medium.com/media/abe07c6c27a316a3e0e1cc7de7f28b51/href</a></iframe><p>In the above case, we have an Observable <strong>endlessly</strong> emitting values <strong>until</strong> the Subscription gets <strong>closed</strong>. After we call .unsubscribe() on each active Subscription we are good and everything is <strong>cleaned up</strong> properly.</p><h4>Mixed case</h4><p>There might be some cases in which the Observable emits the complete or error notifications at some point, but it is not guaranteed that it will always happen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934d0fa212a29f3475963557f54ae9d7/href">https://medium.com/media/934d0fa212a29f3475963557f54ae9d7/href</a></iframe><p>The above code will complete after we click on the button a single time, however if we never do this the Subscription will keep on being active waiting for this single click to happen. So it is safe to assume that we should <strong>unsubscribe</strong>, when we are no longer interested in waiting for this ‘click’ event. For example, if the component or view with that button would get hidden.</p><p>Generally, if you are not sure whether the Observable will emit or has emitted a complete or error notification, you can always call .unsubscribe() — just to be safe. This will <strong>make sure</strong> that the Subscription gets <strong>closed</strong> if it was not and perform proper <strong>clean-up.</strong> If it already was previously closed, nothing extra will happen.</p><h3>What happens after the Subscription ends?</h3><p>To have a full picture of the <strong>Subscription’s lifecycle</strong>, I will show you what happens when the Subscription <strong>ends</strong>.</p><p>By ‘ending the Subscription’ I mean <strong>all ways</strong> in which the Subscription can get closed:</p><ul><li>the Observable’s logic emitting the complete or error notification</li><li>our code calling .unsubscribe() on our Subscription</li></ul><p>After <strong>any</strong> of the above happens, whichever happens first, the <strong>Finalizer/Teardown logic</strong> is called.</p><p>If you have more time, see the video presenting the whole Subscription’s Lifecycle:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbELqpDqU-z4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbELqpDqU-z4&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FbELqpDqU-z4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e880581c6853414c8f7e9737ee6a652/href">https://medium.com/media/0e880581c6853414c8f7e9737ee6a652/href</a></iframe><p>If you have less time, here it is summarized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyiezhCm1hbgaf5w6g5IkA.png" /><figcaption>Lifecycle of a Subscription — from subscribing, through the execution of the Observable and emitting notifications, until the Subscription ends and the Finalizer/Teardown logic gets run</figcaption></figure><p>The <strong>Finalizer/Teardown logic</strong> is provided by the function inside of the Observable and is used to perform <strong>clean-up</strong> and <strong>dispose</strong> actions by the Observable’s logic and to <strong>release</strong> any used resources, abort pending connections and processes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062da0a9a8486d9e4ebe1f34c6cdaf5f/href">https://medium.com/media/062da0a9a8486d9e4ebe1f34c6cdaf5f/href</a></iframe><p><strong>Subscribing</strong> to the above Observable will <strong>add</strong> another handler to the button and <strong>unsubscribing</strong> will <strong>remove</strong> the handler.</p><p>Summarizing, after the Subscription ends, no matter why — by complete or error notifications or unsubscribing — you are good to go. Remember to make sure that <strong>all Subscriptions</strong> to your Observables are <strong>ended</strong>. You might have many Subscriptions made to one Observable and <strong>each one</strong> of them is a <strong>separate execution</strong> of the Observable, so you need to make sure that all of them are closed at some point. Of course, an exception is if you want certain Subscriptions to be active for the whole lifetime of your application.</p><h3>Examples: How to find out if I need to unsubscribe?</h3><p>This is it as far as the theory behind the Subscriptions goes. Let us now see <strong>a few scenarios</strong> and try to <strong>investigate</strong> how do they work as far as the need for <strong>unsubscribing</strong> is concerned.</p><p>It is easy to judge whether we need to <strong>unsubscribe</strong> in a simple case where we know the Observable’s logic well. What about more <strong>complex</strong> scenarios? How to determine whether some Observable completes or not?</p><p>Generally to have the answer you need to <strong>investigate</strong> the whole <strong>logic</strong> of your Observable <strong>step-by-step</strong>.</p><ul><li>What is the main source of the Observable? Does it ever complete? When?</li><li>How are the notifications generated by the source?</li><li>How each of the operators affect the Observable? Does it cause it to complete? Under what circumstances?</li></ul><p>Answering the above questions should guide you towards the answer whether the Observable reliably and always completes or whether you should make sure that your code ends the Subscription explicitly.</p><h4>Simple scenario — of()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83a369d84b8f7cf2bf4a50d9ab471333/href">https://medium.com/media/83a369d84b8f7cf2bf4a50d9ab471333/href</a></iframe><p>In the above case our <strong>source</strong> is the Observable created by using the of() function. Each Subscription to such Observable will <strong>immediately</strong> receive a set of ‘next’ notifications with the provided values (‘Alice’, ‘Ben’ and ‘Charlie’) and then <strong>complete</strong>. As a way to test this, you can try the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7168b979036c60e4516a19398706ef/href">https://medium.com/media/3a7168b979036c60e4516a19398706ef/href</a></iframe><p>This will provide you with the answer what actually happens. After running such code, your console will read:</p><pre>Value: Alice<br>Value: Ben<br>Value: Charlie<br>Completed</pre><p>This means that each time you <strong>subscribe</strong> to this Observable it will <strong>instantly</strong> emit all values and <strong>complete</strong>. And as we already know — after a Subscription receives the complete notification it <strong>ends</strong>, so there is <strong>no need</strong> to unsubscribe.</p><h4>Another simple scenario — fromEvent()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2c46a220d0b00038dd92a99e07eedc/href">https://medium.com/media/ee2c46a220d0b00038dd92a99e07eedc/href</a></iframe><p>Let us start with the <strong>source</strong>. It is an Observable created with the fromEvent function. This means, that this Observable <strong>never completes or errors</strong>. Because of that this Subscription <strong>never ends on its own</strong> and in this particular case we <strong>need to unsubscribe</strong> if we want to stop handling the above ‘click’ event.</p><p>A way to <strong>automatically</strong> complete a Subscription is to add a take(X) operator to the pipeline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934d0fa212a29f3475963557f54ae9d7/href">https://medium.com/media/934d0fa212a29f3475963557f54ae9d7/href</a></iframe><p>This code will react to the <strong>first</strong> click and then <strong>automatically</strong> complete, so <strong>theoretically</strong> you do not need to unsubscribe. That is true if you are sure that this ‘click’ will always happen. If this single ‘click’ would not happen, this Subscription would hang in the memory and be active waiting for that single click to happen. In such case it is best to unsubscribe if, for example, this code is specific to some component and this component is about to get hidden.</p><h4>More complex scenario — multiple operators</h4><p>As you could see above, the operators can <strong>influence</strong> whether the whole Observable created by applying operators <strong>completes or not</strong>, even if the main source <strong>does not</strong> complete. However, in the below case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/475c94d1dbee525b117d5c90a5df8b47/href">https://medium.com/media/475c94d1dbee525b117d5c90a5df8b47/href</a></iframe><p>We have multiple operators and the whole Observable created by using the fromEvent() function and then applying three operators map, filter and tap <strong>still never completes</strong>. This means that it is important to look at the operators from the perspective of how they <strong>handle</strong> the Subscriptions and whether they emit the <strong>complete or error</strong> notifications at some point. The above operators are transparent in this matter — they do not emit the complete notification at any point, contrary to the take(X) operator which we have used previously. The operators here can error if we would provide some faulty code inside of the functions which we have passed to them, but that is an exception handling thing, rather than something we can rely on to always happen.</p><h4>Even more complex scenario — mergeMap()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72daee68c6b68fd69f2396ac34c6e742/href">https://medium.com/media/72daee68c6b68fd69f2396ac34c6e742/href</a></iframe><p>This example is a possible <strong>memory leak trap</strong>! Watch out for such cases in your apps. We should definitely <strong>unsubscribe</strong> from such Subscription, that is due to the fact that the source Observable is created with fromEvent which <strong>does not complete</strong> on its own. Also, we do not have any operators in the pipeline which could change this.</p><p>Now, why is this example such a <strong>danger</strong> to the memory leaks and this pattern might cause <strong>performance issues</strong> if the calculations inside would get more complex?</p><p>There is a mergeMap operator used which creates a <strong>new inner Subscription</strong> for each value/‘input’ event incoming from the source — fromEvent. This inner Subscription is made to the <strong>inner Observable</strong> created using the interval function, which is also a never-ending Observable endlessly emitting values in intervals. And what is worse, as these inner Subscriptions <strong>do not complete</strong>, they will be working as long as the main Subscription is active, due to the way mergeMap operator works. So after many ‘input’ events coming from the fromEvent Observable there will be <strong>a ton of inner Subscriptions</strong> going on.</p><p>If you would <strong>forget</strong> to unsubscribe from the whole <strong>outer Subscription</strong>, the <strong>memory and performance</strong> of the app <strong>might suffer</strong> after some time.</p><p>In the above case it is possible that, instead of mergeMap, another flattening operator should be used, such as switchMap — depending on the desired behavior. The switchMap operator would end the <strong>previous </strong>inner Subscription and <strong>start a new one</strong> for the new value, so there will be at most <strong>one active</strong> inner Subscription.</p><p>Regardless of the above — you should make sure that you <strong>unsubscribe</strong> from this Observable when you no longer need it as it will <strong>not end on its own</strong>.</p><h4>Even more complex scenario</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6992715bbc89f9885f50a1b60304bb13/href">https://medium.com/media/6992715bbc89f9885f50a1b60304bb13/href</a></iframe><p>In the above scenario we have a quite complex Observable. Let us now investigate what happens there to determine whether we need to unsubscribe or whether this Observable will complete on its own.</p><ol><li>The main source of the emissions is an Observable created by the interval(3000) function. This means that once we subscribe to it, it will emit a value every 3 seconds and <strong>never complete</strong>.</li><li>Then, each notification will reach the map operator, which just maps the value to something else. So this operator does not introduce anything which could complete this Observable.</li><li>At this stage of the pipeline we have the exhaustMap operator, which will create new <strong>inner Subscription</strong> based on the value coming from above. So right now we have to take this inner Subscription into consideration — we need to analyze it separately.<br><strong><em>Note:</em></strong><em> If you are not yet familiar with how the flattening operators such as </em><em>switchMap, </em><em>mergeMap, </em><em>concatMap and </em><em>exhaustMap work, it is worth to learn them as they are one of the most useful and at the same time tricky operators to use. I will not explain them in detail here as it is a fairly complex topic that could make a separate article.</em></li><li>As menitoned above, the exhaustMap operator will make a Subscription to the provided <strong>inner Observable</strong> making a new HTTP request to the server by using an Observable created by the ajax function. This Observable <strong>always completes or errors</strong> after the request succeeds or fails.<br><em>For more about the ajax() function see: </em><a href="https://medium.com/@jaywoz/ground-control-to-major-tom-http-calls-in-rxjs-1d47ba964b6c"><em>https://medium.com/@jaywoz/ground-control-to-major-tom-http-calls-in-rxjs-1d47ba964b6c</em></a></li><li>Next, we have two more operators: timeout and catchError. Notice, that these operators are nested. In other words, they are <strong>directly applied</strong> to the Observable created with the ajax() function.</li><li>This means that each notification coming from the Observable created with the ajax function will first reach the timeout and catchError operators. Multiple things can happen at this stage. If the <strong>HTTP call fails</strong> or the a <strong>timeout</strong> happens, the timeout operator will <strong>emit an error</strong> which then would be caught by the catchError operator which will map the outcome to an EMPTY Observable which just immediately <strong>completes</strong>.</li><li>Then, the outcome from the combination ajax — timeout — catchError will reach and be processed by the exhaustMap operator’s logic. The exhaustMap operator passes the values (next notifications) and errors further and does not pass the complete notification coming from the <strong>inner Observable</strong> further. So, even though the inner Observable might complete, the outer/main Subscription will keep on working further.</li><li>Finally, we reach the end of the pipeline of operators, reaching the handlers inside of the subscribe call at the end.</li></ol><p>Gathering all the above points we have a never-ending interval Observable as the source. So we <strong>need to unsubscribe</strong> from it at some point as it will never end on its own. Another thing to note here is that we have the exhaustMap flattening operator which makes additional <strong>inner Subscriptions</strong> to the Observable made from connecting the ajax, timeout and catchError operators. This inner Observable <strong>completes</strong>, however due to the way the exhaustMap flattening operator works this <strong>complete</strong> notification is not passed further down the operator’s chain.</p><p>Summarizing, you should also make sure that you <strong>unsubscribe</strong> in this case.</p><h4>Multiple Subscriptions</h4><p>If you make multiple Subscriptions to your Observable, remember that each Subscription is a <strong>seperate execution</strong> of the Observable, so you need to make sure that <strong>all Subscriptions end</strong> at some point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e578088ec79ee37895fe3d2bddf0f61/href">https://medium.com/media/1e578088ec79ee37895fe3d2bddf0f61/href</a></iframe><p>The above example is trivial, however sometimes you might have many Subscriptions to the same Observable scattered across your app. From <strong>RxJS 7.3.0</strong>, you can use the tap operator to track them when new Subscriptions are made to your Observable and when they end.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4852da5baf7406d24feb7c58eb854d2/href">https://medium.com/media/f4852da5baf7406d24feb7c58eb854d2/href</a></iframe><p>The above will allow you to <strong>debug</strong> your code and <strong>track</strong> when <strong>new Subscriptions</strong> are made to your Observable and whether and when are they closed.</p><h4>Other cases</h4><p>Is your case not covered here? Feel free to <strong>post a comment</strong> with your case, so we can see and <strong>investigate</strong> your case!</p><p>Also, if you are not sure what happens in your case it is worth to put some console.log spies in your code. Please check my article on how you can see what happens in your pipeline of operators: <a href="https://medium.com/@jaywoz/information-is-king-tap-how-to-console-log-in-rxjs-7fc09db0ad5a">https://medium.com/@jaywoz/information-is-king-tap-how-to-console-log-in-rxjs-7fc09db0ad5a</a></p><h3>Try not to need to unsubscribe — Other ways to unsubscribe</h3><p>There are multiple ways which help you to handle the topic of Subscriptions.</p><h4>take(X)</h4><p>If you are interested in receiving <strong>just one value</strong> and then ending the Subscription, you can use the take operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/660df2ea3300be6e91e139172c5e90cd/href">https://medium.com/media/660df2ea3300be6e91e139172c5e90cd/href</a></iframe><p>The above will make the Subscription <strong>complete</strong> after a <strong>single emission</strong>.</p><p><strong>Note:</strong> If your Observable emits just one value and completes, you do not need to do the above, as the result will be exactly the same.</p><h4>takeUntil</h4><p>You can use an Observable, which can be used to <strong>trigger the completion</strong> of the Observable.</p><p>The below Observable will react to the <strong>‘mousedown’ event</strong>, then track the <strong>‘mousemove’ events</strong> until the user triggers the <strong>‘mouseup’ event</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8346b5331a507057f7d83074549cfeb4/href">https://medium.com/media/8346b5331a507057f7d83074549cfeb4/href</a></iframe><p>Also, you can have <strong>multiple Subscriptions</strong> and then use a <strong>single Subject</strong> to complete <strong>all of them</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e1a985d2e54a4596c76012e27bff82c/href">https://medium.com/media/2e1a985d2e54a4596c76012e27bff82c/href</a></iframe><p>When you <strong>initialize</strong> your component you can create <strong>multiple Subscriptions</strong> to various Observables and by using a <strong>common Subject</strong> and the takeUntil operator, you can make <strong>all of these Subscriptions complete</strong>, by making this Subject emit a <strong>single</strong> notification.</p><h4>Angular: `| async` pipe</h4><p>This is a great tool which does all the <strong>subscribing and unsubscribing</strong> for you. When some component or even certain part of your component, which provides a value using the | async pipe, gets shown on the screen, this pipe will <strong>automatically</strong> subscribe to your Observable and once this part gets hidden/destroyed, this Subscription will get <strong>closed</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b5ca76c554a2f067c172c34f98ea3a/href">https://medium.com/media/22b5ca76c554a2f067c172c34f98ea3a/href</a></iframe><p>This is a pseudocode of a component providing two Observables.</p><ul><li>isLoggedIn$ is an Observable using an NgRx-style state,</li><li>items$ fetches the items from an endpoint.</li></ul><p>Let us now have a look at the template part of this component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b208d95fb87d11bf6c1e73279e3eddce/href">https://medium.com/media/b208d95fb87d11bf6c1e73279e3eddce/href</a></iframe><p>In the first line, the async pipe will <strong>subscribe</strong> to isLoggedIn$. Whenever a truthy value gets emitted by this Observable, the list will be shown on the screen. When this happens, another Subscription will be made — this time in line 3. The async pipe will <strong>subscribe</strong> to the items$ Observable, which will make a connection to the server and present the items in the template, once the result comes.</p><p>Then, if the isLoggedIn$ would emit a fasly value, the list would be hidden. The async pipe will handle the <strong>unsubscribing</strong> for us if needed.</p><p>Also, if the whole component gets destroyed, the Subscription to isLoggedIn$ (line 1) will also be <strong>closed</strong>.</p><h4>Angular: Auto-unsubscribing libraries</h4><p>You can use libraries which make it easier to handle the Subscriptions. For example, they can <strong>automatically unsubscribe</strong> when the component gets <strong>destroyed</strong>.</p><p>One of my favorites is the @ngneat/until-destroy npm package.<br>See: <a href="https://github.com/ngneat/until-destroy">https://github.com/ngneat/until-destroy</a></p><h3>Final words</h3><p>As you can see the topic of <strong>Subscriptions</strong> can be <strong>confusing</strong>, so understanding what the Subscriptions and Observables actually are is crucial to know when when should we <strong>unsubscribe</strong> and whether we need to do this at all.</p><p>Make sure you understand the <strong>source Observable</strong> which emits the values and all how all operators you are using work — mostly from the perspective of when and whether they <strong>complete</strong>.</p><p>If you use <strong>Angular</strong>, take advantage of the | async pipe if it works for you in your particular scenario.</p><p>If you have enjoyed this article and want more — please <strong>give a clap</strong> and <strong>follow me: </strong><a href="https://jaywoz.medium.com/">Medium</a>, <a href="https://twitter.com/JerryDoubleU">Twitter</a>, <a href="https://t.co/00MErwahTl?amp=1">LinkedIn</a>. Cheers!</p><h3>New to RxJS?</h3><p>If you are new to RxJS or would like to polish your knowledge, I invite you to have a look at my <a href="https://www.udemy.com/course/rxjs-and-observables/?referralCode=0D36D777BDDAE276C58C"><strong>RxJS and Observables: Introduction</strong></a> course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6f39b8b95b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ground control to major Tom — HTTP calls in RxJS]]></title>
            <link>https://jaywoz.medium.com/ground-control-to-major-tom-http-calls-in-rxjs-1d47ba964b6c?source=rss-d2fd148b034------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d47ba964b6c</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jurek Wozniak]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 20:37:36 GMT</pubDate>
            <atom:updated>2021-09-30T12:50:42.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ground control to major Tom — HTTP calls in RxJS</h3><p>Modern apps make a ton of <strong>HTTP requests</strong>, very often concurrent. <strong>RxJS</strong> is all about handling streams, reacting to values, performing asynchronous actions, so it seems to be a great tool to use in the HTTP area. What options does RxJS give us as far as handling HTTP requests is concerned?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ODWhBzdDTlQ9K_ty" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>XMLHttpRequest and fetch()</h3><p>Let’s start with what options do we actually have available in the browser.</p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><strong>XMLHttpRequest</strong></a> (in short — <strong>XHR</strong>), which dates back to at least 2006, allows us to make HTTP calls. Using it is not the most convenient thing in the world, but it did and still does the job in most cases. To make it more friendly, many easy-to-use wrappers have been created, including the super-popular <a href="https://axios-http.com/">axios</a>.</p><p>Another, more modern option is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"><strong>Fetch API</strong></a> and its <strong>fetch()</strong> method returning a <strong>Promise</strong>, which is a way more convenient interface.</p><h3>The differences</h3><p>The <strong>fetch()</strong> method returns a Promise, which resolves when the HTTP call succeeds and rejects if there is an error. This is very easy to use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7701c9973d96b02b41d571f2df507357/href">https://medium.com/media/7701c9973d96b02b41d571f2df507357/href</a></iframe><p>Using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><strong>XMLHttpRequest</strong></a> (XHR) has plenty of features, but is less convenient to use. See the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff1729e4ae35e9307f414a09186c903/href">https://medium.com/media/dff1729e4ae35e9307f414a09186c903/href</a></iframe><p>This is the <strong>main difference</strong> — nowadays we try to use <strong>Promises</strong> and async/await syntax to conveniently describe asynchronous code. The <strong>callback</strong> solution of the XHR is harder to follow in more complex scenarios.</p><p><strong>Another difference</strong> is that an XHR call provides an easy way to know the <strong>progress</strong>, which is useful when we download or send a bigger file and want to present the progress to the user.</p><p>On the other hand, the <strong>fetch()</strong> method provides a way to get a ReadableStream and process the incoming<strong> data in chunks</strong>, which might be useful when dealing with huge amounts of data.</p><p>Sometimes we want to <strong>cancel the request</strong> when we want to stop sending or fetching some file or we do not care about the response anymore.<br>This is easily accessible when using <strong>XHR</strong>. You can call: xhr.abort();<br>Previously, the fetch() method, due to using a Promise, was not cancellable, however a special signal using <strong>AbortController</strong> was added, which <strong>allows to cancel</strong> calls made by <strong>fetch()</strong>.</p><p>Some might take browser support into consideration, as the <strong>Fetch API</strong> is <strong>newer</strong>, and while it is supported by all modern browsers, this API still gets updated, so it is best to check if all used features are supported by needed browsers.</p><h3>What about RxJS?</h3><p>As you can see, the <strong>two ways</strong> which are available have very different interface and the way we interact with them. The fetch() method, while being more convenient to use does not include all <strong>features</strong> of the less convenient XMLHttpRequest.</p><p>Here comes the <strong>RxJS</strong> with help! The Observables are a great way to wrap the above <strong>HTTP interfaces</strong>. The best news is that RxJS provides many tools to conveniently use <strong>both of them</strong>!</p><p>I have shortly explained the available built-in HTTP interfaces as they are crucial to understand the tools provided by RxJS.</p><p>RxJS provides <strong>two helper functions</strong> returning <strong>Observables</strong> performing HTTP calls:</p><ul><li><strong>ajax()</strong> — using XMLHttpRequest</li><li><strong>fromFetch()</strong> — using fetch()</li></ul><p><strong><em>Note:</em></strong><em> Angular developers will most likely use the built-in </em><a href="https://angular.io/api/common/http/HttpClient"><em>HttpClient</em></a><em> service, which also uses RxJS and Observables and serves as a great way to handle HTTP calls. This article will focus on the features built into RxJS and not cover the </em><a href="https://angular.io/api/common/http/HttpClient"><em>HttpClient</em></a><em> service.</em></p><h3>ajax()</h3><p>The <a href="https://rxjs-dev.firebaseapp.com/api/ajax/ajax">ajax()</a> creation function wraps an <strong>XMLHttpRequest</strong> (XHR) and gives us an <strong>Observable</strong>.</p><p>Performing a simple <strong>GET</strong> operation is super easy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2d24566f15908d724606cfc7400a1e/href">https://medium.com/media/9a2d24566f15908d724606cfc7400a1e/href</a></iframe><p>The great thing is that if the response is a <strong>JSON object</strong>, it will automatically be parsed and provided to us as a regular <strong>JavaScript object</strong>.</p><p>Thanks to this wrapping into an Observable, you get the convenient <strong>error handling</strong> and <strong>composability</strong> — the same as with any other Observable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1049691b74b448940f01ad405aefc802/href">https://medium.com/media/1049691b74b448940f01ad405aefc802/href</a></iframe><h3>fromFetch()</h3><p>The <a href="https://rxjs-dev.firebaseapp.com/api/fetch/fromFetch">fromFetch()</a> creation function returns an <strong>Observable</strong> built on top of the fetch() call using the <strong>Fetch API</strong>.</p><p>Performing a simple <strong>GET</strong> call is also easy, however it does handle things in a more <strong>low-level</strong> fashion. Let’s consider the following code fetching some <strong>JSON</strong> response from an endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1588487b44a0595a547b290879a4f60/href">https://medium.com/media/a1588487b44a0595a547b290879a4f60/href</a></iframe><p>Notice the <strong>selector</strong> option provided to fromFetch(). This is used to tell which part of the <strong>response</strong> do we want to get. It is useful, because if we would like to do something similar to the above code without using the selector field, it would look more like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9104e4f2024f14d00e97f7cb2ce258ee/href">https://medium.com/media/9104e4f2024f14d00e97f7cb2ce258ee/href</a></iframe><h3>Examples — fromFetch vs ajax</h3><p>Let’s now compare how to achieve various <strong>scenarios</strong> when using each function.</p><h4>POST request — ajax()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3904640ce322f2efc7a0721307345c0c/href">https://medium.com/media/3904640ce322f2efc7a0721307345c0c/href</a></iframe><h4>POST request — fromFetch()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878a60d463af6fe8d402154be1e1156f/href">https://medium.com/media/878a60d463af6fe8d402154be1e1156f/href</a></iframe><h4>Cancellation</h4><p>If we want to <strong>abort</strong> an HTTP call, thanks to RxJS, it is super simple in both cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94bf2ffc6462e9425519a9d69eaabce/href">https://medium.com/media/b94bf2ffc6462e9425519a9d69eaabce/href</a></iframe><p>Just <strong>unsubscribe</strong> — the rest is handled for us by RxJS.</p><h4>Progress reporting</h4><p>This one is easily available when using ajax() only.</p><p>If you are interested in the progress of a file you are <strong>downloading</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75a4da463cfe8ef6ced3fc18ccc45773/href">https://medium.com/media/75a4da463cfe8ef6ced3fc18ccc45773/href</a></iframe><p>You can also use it for tracking the <strong>upload</strong> progress.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f0929a529f70e9fd5855e95c111170e/href">https://medium.com/media/7f0929a529f70e9fd5855e95c111170e/href</a></iframe><blockquote>The event.type above can be related to upload_ or download_ and can describe startload, progress or load events. The type is created by combining the prefix with the event. For example, if you are interested in the progress event of the upload process, the event type you are looking for is &#39;upload_progress&#39;.</blockquote><p>It is possible to achieve something similar when using fromFetch(), but it is more complex and not available out-of-the-box.</p><h4>Timeout</h4><p>Thanks to RxJS, this works the same for both.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f1714855319b81e70bf904a19cf6d4/href">https://medium.com/media/79f1714855319b81e70bf904a19cf6d4/href</a></iframe><p>The above will emit an <strong>error</strong> if the HTTP call does <strong>not respond</strong> within 10 seconds.</p><p>It works <strong>the same</strong> for the Observable made with <strong>fromFetch</strong>, so just replace the ajax() call with fromFetch() and it will work the same.</p><h4>Streaming</h4><p>Sometimes we want to handle the incoming <strong>data in batches</strong> and not wait for the response to end and load everything into memory.</p><p>We can do this by using the Observable made with fromFetch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8a69d58605ab4934ef78d0d96021dbf/href">https://medium.com/media/e8a69d58605ab4934ef78d0d96021dbf/href</a></iframe><p>The selector uses the <strong>response.body</strong>, which returns a <strong>ReadableStream</strong>. RxJS will use this stream and emit the incoming values, which we can then can process further, for example in the handler inside of the .subscribe(...) call.</p><h4>Providing default fallback value</h4><p>In many case it is worth to provide some <strong>default response</strong> if the actual call <strong>fails</strong>. For that, use the <strong>catchError</strong> operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/962ab3e76262d87e0713ef3a8fc15b95/href">https://medium.com/media/962ab3e76262d87e0713ef3a8fc15b95/href</a></iframe><h3>Bonus: Autocomplete</h3><p>A great way to use HTTP calls in RxJS is to put them and use somewhere inside of the whole Observable stream.</p><p>For example, imagine that there is an <strong>input text field</strong>, where the user can type in the <strong>search query</strong>. Our code will fetch the <strong>autocomplete suggestions</strong> from the server as the user starts and continues to type and modify the query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a2438dbe3530d60f2e629ce49f7979/href">https://medium.com/media/54a2438dbe3530d60f2e629ce49f7979/href</a></iframe><p>The above code will react <strong>each time</strong> the user <strong>updates the query input</strong>, <strong>debounce</strong> the events if the user types a lot of letters fast, and <strong>send a new HTTP request</strong> to the server.</p><p>Also, if the request takes a bit longer and a new search query will be provided by the user, the previous HTTP request will be <strong>cancelled</strong> and a new HTTP call will be made — this is thanks to the <a href="https://rxjs-dev.firebaseapp.com/api/operators/switchMap"><strong>switchMap</strong></a> operator, which makes sure that <strong>only a single call</strong> is in progress at once and <strong>cancels</strong> the previous ones if there is new query coming from above in the pipeline of operators.</p><p>You can try it yourself in the following sandbox:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-ajax-autocomplete%3Fembed%3D1%26file%3Dindex.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-ajax-autocomplete%3Ffile%3Dindex.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Fsocial_editor-1e53e71ce7e2963fcef1b44837c4570c3fb10c8cb64b194a6eafa4e145d10edc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f881d95e9701d4ff439f4f7f457ecfb7/href">https://medium.com/media/f881d95e9701d4ff439f4f7f457ecfb7/href</a></iframe><p>Start typing in the name of a drink in the <strong><em>“Search query”</em> </strong>field. As soon as you stop for more than <strong>500ms</strong>, a request will be sent to the <strong><em>Cocktail DB API</em></strong>. Then, the response will be mapped into the names of the drinks. Finally, these names will be presented as a list below the query input.</p><p><strong>BTW</strong>, please note the crossDomain: true <strong>ajax()</strong> setting which might be sometimes needed — depending on the configuration of the server you are calling — so the browser can perform a successful <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"><strong>CORS (Cross-Origin Resource Sharing)</strong></a> call. A CORS request is when the domain of your website is different than the one you are trying to reach.</p><p>Go ahead and experiment, change the code. Have fun!</p><h3>Summary</h3><p>As you can see <strong>RxJS</strong> provides great ways to incorporate <strong>HTTP calls</strong> in a convenient and standardized way. Depending on the features needed in your particular scenario and personal preference, the <strong>ajax()</strong> and <strong>fromFetch()</strong> functions are at your disposal. For more features and configuration options, see the docs linked below. Keep experimenting and have fun!</p><p>If you have enjoyed this article, please <strong>give it a clap</strong> and <strong>follow me: </strong><a href="https://jaywoz.medium.com/">Medium</a>, <a href="https://twitter.com/JerryDoubleU">Twitter</a>, <a href="https://t.co/00MErwahTl?amp=1">LinkedIn</a>. Thank you!</p><h3>Useful links</h3><ul><li><a href="https://rxjs-dev.firebaseapp.com/api/ajax/ajax">RxJS docs: ajax()</a></li><li><a href="https://rxjs-dev.firebaseapp.com/api/fetch/fromFetch">RxJS docs: fromFetch()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">MDN: XMLHttpRequest — XHR</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">MDN: Fetch API — fetch()</a></li></ul><h3>New to RxJS?</h3><p>If you are new to RxJS or would like to polish your knowledge, I invite you to have a look at my <a href="https://www.udemy.com/course/rxjs-and-observables/?referralCode=0D36D777BDDAE276C58C"><strong>RxJS and Observables: Introduction</strong></a> course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d47ba964b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Information is King — tap() — how to console.log in RxJS]]></title>
            <link>https://jaywoz.medium.com/information-is-king-tap-how-to-console-log-in-rxjs-7fc09db0ad5a?source=rss-d2fd148b034------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc09db0ad5a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jurek Wozniak]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 06:20:31 GMT</pubDate>
            <atom:updated>2021-09-30T12:59:42.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>Information is King — tap() — how to console.log in RxJS</h3><p>We all know and love the mighty console.log. Every time we need to see certain value at certain stage of our function we eagerly put it in every other line. How can we achieve such behavior in the <strong>RxJS</strong> world of <strong>Observables</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lgIOJpakJ4qF6vMYhw_Sw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ratushny?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dmitry Ratushny</a> on <a href="https://unsplash.com/license?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The tap() operator</h3><p>Here comes the tap() operator. It does not influence the Observable stream in any way and just passes all notifications through without modifying them. You might ask why would we use such operator if it does not do anything? It can be used to provide <strong>side-effects</strong> at any stage of the operators pipeline, which is what we need if we want to spy on our Observable and see what happens inside.</p><p>Let’s consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47eb82dd6801f232b9fe5350ea67f684/href">https://medium.com/media/47eb82dd6801f232b9fe5350ea67f684/href</a></iframe><p>This puts our, let’s call it, spy inside of this Observable’s pipeline. Each time some value passes through the filter() operator, it will get logged to the console just before the value reaches the map() operator. This is <strong>very useful for debugging</strong>, and also learning about Observable streams.</p><h3>Where can I put it?</h3><p>You can put the tap() operator <strong>at any stage</strong> of the pipeline.</p><p>For example, if you put it as the first one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dec641c7ae8a63a407a892ad8deb9a9/href">https://medium.com/media/1dec641c7ae8a63a407a892ad8deb9a9/href</a></iframe><p>It will receive the same exact notifications that will be emitted by the source, which in our case is someObservable$.</p><p>If you put it at the end:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/305eb42438fe1763be1b2b6570a02579/href">https://medium.com/media/305eb42438fe1763be1b2b6570a02579/href</a></iframe><p>The logged values will be exactly the same as those which reach the function inside of the subscribe() call at the end.</p><h3>Handling other notification types</h3><p>In the above examples we just console.logged the emitted values.</p><p>The values in RxJS are emitted by using <strong>‘next’</strong> notifications. The Observables can also emit other notification types such as <strong>‘error’</strong> or <strong>‘complete’</strong>. The tap() operator can also react to those. To do so, you need to provide an object containing handlers for the notification types you want to handle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15624378beeeaaf9d1d6c3cb226d0469/href">https://medium.com/media/15624378beeeaaf9d1d6c3cb226d0469/href</a></iframe><p>You do not need to provide handlers for all notification types. You can choose just the ones that you need and omit the rest.</p><h3>One more thing…</h3><p>Starting from <strong>RxJS 7.3.0</strong>, the tap() operator can do even more. You can see when the Subscription starts and ends at the level of the tap() operator.</p><p>On top of the ‘next’, ‘error’ and ‘complete’ handlers which we have discussed above, the tap() operator introduces three more handlers:</p><ul><li><strong>subscribe</strong> — called when a new Subscription is made,</li><li><strong>unsubscribe</strong> — called when the Subscription is closed by unsubscribing (calling unsubscribe); this will <strong>NOT</strong> be executed when ‘error’ or ‘complete’ is emitted,</li><li><strong>finalize</strong> — called when the Subscription ends, no matter what the cause: it can be either unsubscribing, an error or a complete notification; all will cause the ‘finalize’ handler to be called.</li></ul><p>Example usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64b5fe21a0886a34bbcda375d8c43efd/href">https://medium.com/media/64b5fe21a0886a34bbcda375d8c43efd/href</a></iframe><p>Remember that those callbacks are executed by thetap() operator, so these handlers will be executed by the notifications and Subscription events that happen at the level of the tap() operator — not the whole Subscription.</p><p>To show you what I mean, let me show you this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9bd3956f4b8a990853a08cec62710c/href">https://medium.com/media/2f9bd3956f4b8a990853a08cec62710c/href</a></iframe><p>In the above example, we can track when the Subscriptions made by the switchMap() operator are created and ended.</p><p>As you can see, within one Observable there can happen a lot of inner Subscriptions and the tap() operator can help us track and learn how it all happens and when.</p><h3>Conclusion</h3><p>The tap() operator can act as a <strong>debugging</strong> tool in the RxJS world just as our favorite friend — console.log did in the regular JavaScript universe. In fact, the tap() operator allows us to put the console.log calls inside of the pipeline of operators and spy on the emitted values and other notifications. Also, we can spy and track the Subscriptions as they come and go at any stage of the pipeline. All these features are a great way not only to debug but also learn how things work in RxJS!</p><p><strong>Thank you</strong> for reading! If you have enjoyed this article please <strong>give it a clap</strong> and <strong>follow me</strong> (<a href="https://jaywoz.medium.com/">Medium</a>, <a href="https://twitter.com/JerryDoubleU">Twitter</a>, <a href="https://t.co/00MErwahTl?amp=1">LinkedIn</a>) to see more stuff like this.</p><p>I know that the tap() operator allows much more than debugging and adding console.logs. Let me know how do you use the tap() operator in the comments section! As a bonus, have a go in the Stackblitz playground below and try the tap() operator on your own!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-tap-playground%3Fdevtoolsheight%3D33%26embed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-tap-playground%3Fdevtoolsheight%3D33%26embed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Fsocial_editor-1e53e71ce7e2963fcef1b44837c4570c3fb10c8cb64b194a6eafa4e145d10edc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aabb12e9503dd5a92003f298a7985c9/href">https://medium.com/media/8aabb12e9503dd5a92003f298a7985c9/href</a></iframe><h3>New to RxJS?</h3><p>If you are new to RxJS or would like to polish your knowledge, I invite you to have a look at my <a href="https://www.udemy.com/course/rxjs-and-observables/?referralCode=0D36D777BDDAE276C58C"><strong>RxJS and Observables: Introduction</strong></a> course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc09db0ad5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>