<?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 Nicholas Cunningham on Medium]]></title>
        <description><![CDATA[Stories by Nicholas Cunningham on Medium]]></description>
        <link>https://medium.com/@ndcunningham?source=rss-929862e54c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U5AV8iTy5nUAyn3XDKMGQw@2x.jpeg</url>
            <title>Stories by Nicholas Cunningham on Medium</title>
            <link>https://medium.com/@ndcunningham?source=rss-929862e54c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:50:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ndcunningham/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[Determine your User Location with Netlify Edge Functions]]></title>
            <link>https://medium.com/nrwl/determine-your-user-location-with-netlify-edge-functions-a252c121c284?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a252c121c284</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Fri, 26 May 2023 17:02:18 GMT</pubDate>
            <atom:updated>2023-06-05T08:06:55.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2ynKDm6DIKLcZ2fJlV0dw.png" /></figure><p>Today, we will explore how to use @nx/netlify serverless functions to determine a user’s location. This can be an incredibly useful feature in various applications, such as customizing user experiences based on their region, displaying localized content, or tracking user demographics for marketing purposes. In this post, we’ll walk you through a step-by-step guide on implementing this functionality using @nx/netlify serverless functions.</p><p>Before we get started though, here’s a video introduction to the new @nx/netlify package:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FidH6GCkWq0w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DidH6GCkWq0w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FidH6GCkWq0w%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/cb5c31447b34d80d09f7d3f3f953a1e2/href">https://medium.com/media/cb5c31447b34d80d09f7d3f3f953a1e2/href</a></iframe><h4>Step 1: Set up your Nx workspace with Netlify</h4><p>To get started, you need to have an Nx workspace. If you haven’t already, create a new Nx workspace by running:</p><pre>npx create-nx-workspace user-location --preset=@nx/netlify</pre><p>This should create a default function inside src/functions/hello/hello.ts, which can be <em>safely deleted</em> if necessary.</p><h4>Step 2: Create a serverless function</h4><pre>mkdir src/functions/user-location<br>touch src/functions/user-location/user-location.ts</pre><h4>Step 3: Determine the user’s location</h4><p>To determine the user’s location, we will leverage the request.headers object, specifically the x-forwarded-for header containing the user’s IP address. We can then use an IP geolocation API like ipapi (<a href="https://ipapi.co/">https://ipapi.co/</a>) to fetch location data based on this IP address.</p><p><em>Note</em> in <strong>Node.js 18</strong>, the experimental global fetch API is available by default. If you are using a node version <strong>lower</strong> than <strong>18</strong> you can install node-fetch to handle API requests:</p><pre>npm install node-fetch</pre><p>Now, update the user-location.ts file with the following code:</p><pre>import { Handler } from &quot;@netlify/functions&quot;;<br>import fetch from &quot;node-fetch&quot;; // Can be removed if node &gt;= 18<br><br>export const handler: Handler = async (event, _) =&gt; {<br>  const ip = event.headers[&quot;x-forwarded-for&quot;];<br>  const url = `https://ipapi.co/${ip}/json/`;<br>  try {<br>    const response = await fetch(url);<br>    const data = await response.json();<br>    return {<br>      statusCode: 200,<br>      body: JSON.stringify({<br>        location: {<br>          city: data.city,<br>          region: data.region,<br>          country: data.country,<br>        },<br>      }),<br>    };<br>  } catch (error) {<br>    return { statusCode: 500, body: `Error fetching user location` };<br>  }<br>};</pre><h4>Step 4: Deploy your serverless function</h4><p>When we created our workspace, the initial scaffolding generated a <strong>deploy-target</strong> inside our project.json.</p><blockquote>A <strong>target</strong> is a specific task you can run for a project.<br>You can think of it as a script/command that does a specific job. The most common targets are “build”, “serve”, “test”, “lint”, “deploy”, etc. For more information regarding project.json you can read about it at <a href="https://nx.dev/reference/project-configuration">project-configuration</a></blockquote><p>We can start off by creating our site on Netlify by running:</p><pre>npx netlify init</pre><p>After you have answered all the prompts your site should be created. A .netlify folder should be created with references to your newly created site.</p><p>Now, to deploy your serverless function run:</p><pre>nx run deploy</pre><p>Finally, navigate to your Netlify site’s Functions tab, and you should see your user-location function deployed and ready to use!</p><p>For example, ours can be found at: <a href="https://644a9b17d0299b00b581b33f--find-user-location.netlify.app/.netlify/functions/user-location">https://644a9b17d0299b00b581b33f--find-user-location.netlify.app/.netlify/functions/user-location</a></p><pre>{&quot;location&quot;:{&quot;city&quot;:&quot;Miami&quot;,&quot;region&quot;:&quot;Florida&quot;,&quot;country&quot;:&quot;US&quot;}}</pre><p>By following these steps, you’ve successfully used @nx/netlify serverless function to determine a user’s location!</p><h4>Wrapping up</h4><p>Never used Nx before? Learn more about Nx <a href="https://nx.dev/getting-started/why-nx">here</a>.<br><a href="https://nx.dev/recipes/deployment/node-serverless-functions-netlify#configure-your-netlify-deploy-settings">Official recipe from Nx</a><br><a href="https://github.com/ndcunningham/nx-netlify-serverless">Github example</a></p><h4>Learn more</h4><p>🧠 <a href="https://nx.dev/">Nx Docs</a><br>👩‍💻 <a href="https://github.com/nrwl/nx">Nx GitHub</a><br>💬 <a href="https://go.nrwl.io/join-slack">Nrwl Community Slack</a><br>📹 <a href="https://www.youtube.com/@nxdevtools">Nrwl Youtube Channel</a><br>🚀 <a href="https://nx.app/">Speed up your CI</a></p><p>Also, if you liked this, click the ❤️ and make sure to follow <a href="https://twitter.com/ndcunningham">Nicholas</a> and <a href="https://twitter.com/NxDevTools">Nx</a> on Twitter for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a252c121c284" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nrwl/determine-your-user-location-with-netlify-edge-functions-a252c121c284">Determine your User Location with Netlify Edge Functions</a> was originally published in <a href="https://medium.com/nrwl">Nx Devtools</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an Autocomplete Bar With Accessibility in Angular]]></title>
            <link>https://ndcunningham.medium.com/autocomplete-accessibility-angular-d0aa2bd8117b?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0aa2bd8117b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 20:24:05 GMT</pubDate>
            <atom:updated>2021-01-08T19:31:24.168Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building autocomplete for those who use computers differently</h4><figure><img alt="Clay pots" src="https://cdn-images-1.medium.com/max/1024/0*ynPICK23oamPJRNh" /><figcaption>Photo by <a href="https://unsplash.com/@tomcrewceramics?utm_source=medium&amp;utm_medium=referral">Tom Crew</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>It’s very easy to understand the functionality of common tools used on the web. A common oversight but essential part of developing these tools is to ensure that they are accessible to everyone. Like most other engineers, I was taught to build tools to be functionally sound. Accessibility has always been an afterthought.</p><blockquote>“You might also think of accessibility as treating everyone the same, and giving them equal opportunities, no matter what their ability or circumstances. Just as it is wrong to exclude someone from a physical building because they are in a wheelchair (modern public buildings generally have wheelchair ramps or elevators), it is also not right to exclude someone from a website because they have a visual impairment. We are all different, but we are all human, and therefore have the same human rights.” — <a href="https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility">MDN Web Docs</a></blockquote><p>Let’s go over the requirements that we would like to meet:</p><ul><li>As a user, I would like to be able to type in a search for movies.</li><li>As a user, I would expect a list of movies to be shown after a short delay during typing.</li><li>As a user, after the list of movies is shown, I should be able to use the arrow keys to navigate the list without changing my focus.</li></ul><p>Building the component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b6c2f77ce2e08b4c3b9b05e7f320265/href">https://medium.com/media/5b6c2f77ce2e08b4c3b9b05e7f320265/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fb599cacb992d61d1054a4c36200555/href">https://medium.com/media/9fb599cacb992d61d1054a4c36200555/href</a></iframe><p>Here’s an explanation of the attributes that you don’t normally see:</p><ul><li>aria-autocomplete — Indicates what to expect when inputting text into the control.</li><li>role — Indicates that this element has a combination of another element that may dynamically pop up to help the user with setting the text.</li><li>attr.aria-expanded — Self-explanatory, but simply put, it highlights when the list of movies is showing.</li><li>autocomplete — Tells the browser how to handle the autocomplete of forms. Here, we set it to none so we can clearly see the movie results without an overlapping autocomplete based on previous inputs.</li></ul><p>Now we need to describe how the results will be shown:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/544ee0e3d635ecfd86b4c9da76c868c4/href">https://medium.com/media/544ee0e3d635ecfd86b4c9da76c868c4/href</a></iframe><p>For the input, we added:</p><ul><li>aria-owns — Gives a contextual/functional relationship between the input search as the parent and the ul li elements as the child.</li><li>aria-activedescendant — Indicates which element in the list is active while the focus is on our combo input box.</li></ul><p>To be semantically accurate, we also added ul and li elements that should show the list of movies.</p><p>We should now have something like this:</p><figure><img alt="Autocomplete bar" src="https://cdn-images-1.medium.com/max/1024/1*imS8jt9X5s2PUJnTitHUtw.png" /></figure><p>I won’t go over the API aspect of it where you type and get results. This component’s responsibility is to show the movies whenever the parent passes it down.</p><h3>Secret Sauce: Angular CDK</h3><p>We already have our input and the movies will be shown whenever the parent passes it down. So now we need to be able to navigate with the up and down arrow keys and select with enter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def1334b9517e30ba56ae1dc3165f324/href">https://medium.com/media/def1334b9517e30ba56ae1dc3165f324/href</a></iframe><p>This directive allows us to do a few things. Firstly, this implements Highlightable, which is a class from the @angular/cdk/a11y lib. It is used in conjunction with ActiveDescendantKeyManager (see below), which is also from @angular/cdk/a11y . The main purpose of this is to correctly handle keyboard events across multiple browsers via a single API. You can read more about this on <a href="https://material.angular.io/cdk/a11y/overview">Angular Material’s website</a>.</p><p>Secondly, this directive will be on each movie result. As such, we have an active class to identify.</p><p>Lastly, we have a getItem function that we can access from our autocomplete when the user selects an item.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70d1e9d45002b5d86342086c728e903e/href">https://medium.com/media/70d1e9d45002b5d86342086c728e903e/href</a></iframe><pre>&lt;li role=&quot;option&quot; appLiAutocomplete *ngFor=&quot;let movie of movies&quot;&gt; <br>{{ movie }}&lt;/li&gt;</pre><p>We update our autocomplete component to work the directive via ActiveDescendantKeyManager. This update will query our template for our directive. The withWrap function ensures that if we are at the end of the list, it will start back at the top (and vice versa).</p><p>Lastly, on our keyup event for our input, we want to update this to handle arrow keys in addition to when the user is searching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/996b9f9d79f29c845a8422a007628bcf/href">https://medium.com/media/996b9f9d79f29c845a8422a007628bcf/href</a></iframe><ul><li>Lines 2-5 ensure that if we are pressing the arrow keys, the text inside the input won’t emit another event to the parent to start the search.</li><li>Line 6 allows us to get the item that is currently highlighted.</li><li>Line 7 checks if the event key pressed is the enter key, which will output to the parent as the selected item.</li><li>Line 10 will handle if the user pressed the up or down arrows, which item needs to be highlighted, and if the item needs to wrap up or down.</li></ul><p>And that’s pretty much it!</p><p>Using this approach gives you the separation of concerns and you can easily extend this accessibility for each li element by updating the directive.</p><p>Additionally, the benefit of adding this accessibility will be really appreciated for many users who are non-visual or use assistive technology when they are on the web.</p><p>See the full code on <a href="https://stackblitz.com/edit/angular-ivy-nzubf2?embed=1&amp;file=src/app/autocomplete/autocomplete.component.ts">Stackblitz</a> and check me out on <a href="https://twitter.com/ndcunningham">Twitter</a> or <a href="https://www.linkedin.com/in/nicholascunninghamm">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0aa2bd8117b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Awesome RxJS Observables and Operators That Are Often Overlooked]]></title>
            <link>https://ndcunningham.medium.com/5-awesome-rxjs-observables-and-operators-that-are-often-overlooked-726c300308dc?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/726c300308dc</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 01:02:10 GMT</pubDate>
            <atom:updated>2019-12-13T01:02:10.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pluck, Defer, FromEvent, and more</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*GKSVoYbEX8Qi6RNV" /><figcaption>Photo by <a href="https://unsplash.com/@heftiba">Toa Heftiba</a> at <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>When using RxJS, often people remember the array operators such as map, filter, reduce, etc…</p><p>Although I highly recommend using them whenever possible for the <em>right reasons,</em> it can be also said that using another operator that is more specialized can result in the possibility of a smaller code print or improved readability for another developer.</p><p>Here, I will try to highlight some that I use when these scenarios arise.</p><h3>1. Pluck</h3><p>Maps each source value (an object) to its specified nested property.</p><p>Let’s start off with<em>, </em>which can be very similar to, however, it only takes <em>one selected property</em><strong><em> </em></strong>off every emitted object. It actually uses the <a href="https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/pluck.ts">map</a> operator underneath.</p><p>Let’s say we have an interface, declared as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22705d3826a4f81516e6003f2c047cd4/href">https://medium.com/media/22705d3826a4f81516e6003f2c047cd4/href</a></iframe><p>And now we have an object like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92cdaa86078420f36b7c0c5f72a71051/href">https://medium.com/media/92cdaa86078420f36b7c0c5f72a71051/href</a></iframe><p>Let’s say we want to select all the names, here is how we would do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7aa0d7166c08d9899ff11a2a2d849dd/href">https://medium.com/media/c7aa0d7166c08d9899ff11a2a2d849dd/href</a></iframe><p>And for each house street:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e665bf4f77cb4d0647c9213a8fca54d/href">https://medium.com/media/9e665bf4f77cb4d0647c9213a8fca54d/href</a></iframe><h3>2. Defer</h3><p>Creates an observable that is lazy, i.e. active only upon subscribe.</p><p>This highlights one difference between promise and observables.</p><p>Where promises are eager, we can use <a href="https://rxjs.dev/api/index/function/defer">defer</a> to delay our observable executing. You might have guessed that the naming probably implies what it does. This can be also called a <em>cold observable</em>.</p><p>Let’s say we have an Angular application that listens to click events and returns the date when it was clicked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a11f6a320112cf9f9288de07de3e2e/href">https://medium.com/media/56a11f6a320112cf9f9288de07de3e2e/href</a></iframe><p>To fix this problem, add a defer<strong>.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a65b37b83e3ad1a059fbf34a10cba9e4/href">https://medium.com/media/a65b37b83e3ad1a059fbf34a10cba9e4/href</a></iframe><p>Just a bit of context. We used fromEvent which is a <em>hot observable</em> (eager by default) and turned it <em>cold</em> by using defer.</p><p>That leads to a great segue for FromEvent.</p><h3>3. FromEvent</h3><p>It creates an observable that emits based on an event type from an event target.</p><p>As I showed earlier, <a href="https://rxjs-dev.firebaseapp.com/api/index/function/fromEvent">fromEvent</a> can take up to three params. <br>1. Is the target where the event will be fired.<br>2. Is the name of the event that we want to listen to.<br>3. Is an optional listener of options.</p><p>It is effectively addEventListener and removeEventListener wrapped into one. You can pass the listener options, such as passive, captureand once with an optional third parameter.</p><p>If you want more info on these details you can visit <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">AddEventListener</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02db8a6d63d52ffe76ea64d6f4d98fae/href">https://medium.com/media/02db8a6d63d52ffe76ea64d6f4d98fae/href</a></iframe><p>This displays the similarity between RxJS and JavaScript because the underlying function used is <em>actually</em> add/removeEventListener.</p><h3>4. ExhaustMap</h3><p>Returns an observable after applying the projected function. If the source emits another observable while the previous is still running the new emission will be ignored.</p><p>Now, the use of this is a special uses case and, often, there is no need to use it. <br>However, I wanted to highlight why it could be useful.</p><p>Let’s say we are making a payment which is attached to a button click and we have set up our logic like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/236e9e7858c8495666f5a36510c79536/href">https://medium.com/media/236e9e7858c8495666f5a36510c79536/href</a></iframe><p>Now, <a href="https://rxjs-dev.firebaseapp.com/api/operators/mergeMap">mergeMap</a> is just a flattening operator. That means it takes an observable source and returns a new observable which will be unwrapped. So, the pay function of payService will have to return an observable.</p><p><a href="https://rxjs-dev.firebaseapp.com/api/operators/exhaustMap">exhaustMap</a> is also a part of the flattening family (it’s a combination of <a href="https://rxjs-dev.firebaseapp.com/api/operators/exhaust">exhaust</a> + <a href="https://rxjs-dev.firebaseapp.com/api/operators/map">map</a>) as is mergeMap (<a href="https://rxjs-dev.firebaseapp.com/api/operators/mergeAll">mergeAll</a> + <a href="https://rxjs-dev.firebaseapp.com/api/operators/map">map</a>. I know, not a bit different).</p><p>However, you can see the issue we have here. The user would be able to click <em>pay</em> multiple times, effectively performing multiple requests.</p><p>Of course, you could disable the button after the first click but the event stream should also be protected.</p><p>This can be solved with our exhaustMap because while the inner observable pay is being executed via HTTPS request and response, all other emissions will be ignored.</p><h3>5. ObserveOn</h3><p>It allows you to run your observable emissions on a scheduler provided.</p><p>Now, <a href="https://rxjs-dev.firebaseapp.com/api/operators/observeOn">observeOn</a> brings you into the realm of scheduling which I won’t dive into, but I will provide some great links that you should definitely check out.</p><p>However, there are times when we would like to control where events are queued, for example, to enhance performance or user experience.</p><p>In one of the previous blogs I posted, <a href="https://medium.com/better-programming/drag-and-drop-made-easy-with-rxjs-8cd4a8994a07"><em>Drag &amp; Drop made easy with RxJS</em></a><em>,</em> I illustrated the final solution by using <a href="https://rxjs-dev.firebaseapp.com/api/operators/subscribeOn">subscribeOn</a> to change when the repaint should occur from the default <a href="https://rxjs-dev.firebaseapp.com/api/index/const/asyncScheduler">asyncScheduler</a> to <a href="https://rxjs-dev.firebaseapp.com/api/index/const/animationFrameScheduler">animationFrameScheduler</a>.</p><p>This really means that we shouldn’t queue our emission on the task queue but on the animationFrame queue to get a smoother/higher frame rate paint.</p><p>This type of technique usually is beneficial when doing animations as well.</p><p>Take a look at my post to see more and it should expose you to other operators that I didn’t mention.</p><p>More on scheduling:</p><ul><li>A great video by Michael Hladky:<a href="https://www.youtube.com/watch?v=wfSKE7GtKhU"> <em>RxJs schedulers from outer space</em></a><em>.</em></li><li>An old but still effective read from André Staltz: <a href="https://staltz.com/primer-on-rxjs-schedulers.html"><em>Primer on RxJS schedulers</em></a><em>.</em></li></ul><p>I tried not to have a long post for this one but I couldn’t avoid getting into some details.</p><p>Keep on sharing the knowledge. It will only make us stronger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=726c300308dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Drag and Drop Container using RxJS]]></title>
            <link>https://ndcunningham.medium.com/how-to-build-a-drag-and-drop-container-using-rxjs-7c15dab8a70c?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c15dab8a70c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 14:50:12 GMT</pubDate>
            <atom:updated>2019-09-03T20:46:28.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Build a Drag and Drop Container Using RxJS</h3><p>Create an effective drag and drop container using only RxJS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*P3ZY0Oka9Hi3iVKP" /><figcaption>Photo by <a href="https://unsplash.com/@joaosilas">João Silas</a> at<a href="http://www.unsplash.com/"> Unsplash</a></figcaption></figure><p>Drag and drop has been a necessary feature for many web applications, whether for uploading images or reorganizing information. It is an intuitive way of giving user interaction, without the need for words.</p><p>This is what we will be creating today!</p><p>I’ll start off by defining <a href="https://rxjs-dev.firebaseapp.com/guide/overview">RxJS</a>, in case this is the first you’ve heard of it.</p><blockquote>RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.</blockquote><p>Basically, it allows the developer to break down multiple async code and compose them so that they can be read sequentially — and easily understood (I’m talking about reading with your eyes) — even though the code is async.<br>This article will show you how to break up and compose the async code.</p><p>I will be using the Angular framework but I would like to highlight that this is <em>not needed — </em>the steps can be used regardless of frameworks. All you need is the RxJS library (NPM, UMD, etc…).</p><p>First off we will create the container by which the user gets a visual. We will call this our <em>dropzone</em>.</p><pre>&lt;div class=&quot;dropzone&quot; #dropZone&gt;<br>	&lt;span&gt; Drop Zone &lt;/span&gt;<br>&lt;/div&gt;<br><br>&lt;style&gt;<br>.dropzone {<br>  border: 1px dashed green;<br>  height: 200px;<br>  width: 100%;<br>  display: flex;<br>  justify-content: center;<br>}<br><br>.dropzone span {<br>  margin: auto 0;<br>}<br>&lt;/style&gt;</pre><p>Next, we hook up our RxJS Observable to the dropzone element to start listening for events which we’re interested in. Let’s start off with the dragEnter event. This event basically, will notify you when the user has entered our container by dragging. In Angular, it looks something like this:</p><pre>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent implements OnInit {<br><br>  @ViewChild(&#39;dropZone&#39;, { static: true }) dropZone: ElementRef&lt;HTMLDivElement&gt;;<br><br>  dragEnter$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;dragenter&#39;)).pipe(<br>    tap((event: any) =&gt; { event.target.style.background = &#39;teal&#39;; event.target.style.opacity = .5; })<br>  );<br>  <br>  ngOnInit() {<br>    this.dragEnter$.subscribe();<br>  }<br>}</pre><p>We get defer fromEvent from importingrxjs and tap from import rxjs/operators .</p><p>fromEvent listens for the dragenter event, taking the element you want to start listening to and the event you would like to listen to. <br>However, I wrapped it in a defer because fromEvent is hot — which means it will immediately check even before the UI has been rendered. This will cause a null to be thrown to the this . Using defer will only start checking only after we subscribe so effectively it makes it cold.</p><p>Finally, I used tap because I’m not affecting the observable’s output but would like to do something on the side after this event has fired. This is called a side-effect. So if you have an observable and want to add some feature or functionality without affecting the data emitted by the observable you can use tap.</p><p>Test this out and see the result. You’ll realize that it changes but does not reset if you drop or move the mouse away from the element.</p><h4>Why?</h4><p>This happens because we’re not listening to any leave or exit event — the code does not know unless you tell it!</p><p>Let’s add these, which are similar to the first.</p><pre>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent implements OnInit {<br><br>  @ViewChild(&#39;dropZone&#39;, { static: true }) dropZone: ElementRef&lt;HTMLDivElement&gt;;<br><br>  dragEnter$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;dragenter&#39;)).pipe(<br>    tap((event: any) =&gt; { event.target.style.background = &#39;teal&#39;; event.target.style.opacity = .5; })<br>  );<br><br>  dragExit$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;dragleave&#39;)).pipe(<br>    tap((event: any) =&gt; { event.target.style.background = &#39;&#39;; event.target.style.opacity = 1; })<br>  );<br><br>  dragEnd$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;dragend&#39;)).pipe(<br>    tap((event: any) =&gt; event.target.style.background = &#39;&#39;)<br>  );<br>  <br>  ngOnInit() {<br>    this.dragEnter$.subscribe();<br>    this.dragEnd$.subscribe();<br>    this.dragExit$.subscribe();<br>  }<br>}</pre><p>These are the definitions for the additional events:</p><ul><li>dragend event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).</li><li>dragleave event is fired when a dragged element or text selection leaves a valid drop target.</li></ul><p>With these in place, if we drag over and leave or drop it, it should reset to the original state.</p><h3>Drop Time</h3><p>Now to add the drop all we need to is to add a drop event similar to the above right?</p><p>Nope! Actually, you have to add another event to allow the drop to occur as already explained earlier the code is similar to the above:</p><pre>dragOver$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;dragover&#39;)).pipe(</pre><pre>tap((event) =&gt; { event.preventDefault(); })</pre><pre>);</pre><p>With that in place now we can drop code and we should be done!</p><pre>drop$ = defer(() =&gt; fromEvent(this.dropZone.nativeElement, &#39;drop&#39;)).pipe(<br> tap((event: any) =&gt; {<br>  event.preventDefault();<br>  event.target.style.background = &#39;&#39;;<br>  console.log(event.dataTransfer.files[0].name);<br> }));</pre><p>In this scenario, we would only display the name in the console. However, you can do just about anything here since the hard part is already done!</p><p>Just remember to add a subscribe for your new events:</p><pre>this.dragOver$.subscribe();<br>this.drop$.subscribe();</pre><p>Done! That was easy, right?</p><h4>Composition</h4><p>We could leave it as is and it would work as expected. However, let’s make this a bit cleaner. This is where the magic of composition happens. Just to add a little more thought into how to clean up after you have registered listeners.</p><p>Whenever you subscribe you’re effectively adding a addEventListener to that element. So, in order not to abuse the user’s memory you should clean up when you’re finished.</p><p>There are many ways to compose this, I am just showing you one.</p><p>We will create a new observable that will pull from all the other broken down observable and unsubscribe which is removeEventListner.</p><pre>dragAndDrop$ = this.dragEnter$.pipe(<br> mergeMap(() =&gt; this.dragOver$),<br> switchMap(() =&gt; merge(this.dragExit$.pipe(first()),  this.drop$.pipe(takeUntil(this.dragEnd$)))));</pre><p>Let’s read this sequentially and it should be understood with a bit of explanation.</p><p>First, we listen to the dragEnter event.</p><p>After that event has fired we ensure that we can drop via dragOver</p><p>We listen for the first dragExit event, or a drop event which waits until the dragEnd event is fired when that happens the takeUntil will clean up after itself when the user has released the mouse.</p><p>With this composition, we can remove all the other subscribes leaving only this:</p><pre>this.dragAndDrop$.subscribe();</pre><p>Now we have clean and separate events, which we can do side-effects with without disturbing the emissions that allow us to compose complex operations, such as our dragAndDrop$.</p><p>I can guarantee is that if you did this with vanilla JavaScript it would not be as simple and more often than not buggy with not the best memory management. If you would like to go the extra-mile, though not necessary, you can add a takeUntil to the dragAndDrop$ observable so when the component is destroyed it will clean up that observable memory.</p><p>I explain more of this in <a href="https://medium.com/swlh/why-completing-unsubscribing-your-observable-stream-is-important-f96b513e83c1">Why Completing your Observable is important</a>.<br>The demo can be view here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dropzone-drag-n-drop%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fapp.component.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dropzone-drag-n-drop%3Ffile%3Dsrc%252Fapp%252Fapp.component.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.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/c6291c4faa933c07b2db65c066bcfe09/href">https://medium.com/media/c6291c4faa933c07b2db65c066bcfe09/href</a></iframe><p>Keep on sharing the knowledge. It will only make us stronger!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c15dab8a70c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Consider Using TypeScript Generics Instead of Any]]></title>
            <link>https://ndcunningham.medium.com/why-you-should-consider-using-typescript-generics-instead-of-any-4c6543ba88ec?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c6543ba88ec</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 00:11:56 GMT</pubDate>
            <atom:updated>2019-08-22T19:40:36.145Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick overview of a powerful feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*QR7INRnSJGYm7uBY" /><figcaption>Photo by<a href="https://unsplash.com/@jangus231"> Joshua Ang</a> at <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>TypeScript has provided us with many opportunities for JavaScript. One of those is <em>type safety</em> checking at <em>compile time</em>.</p><p>In this article, we will briefly go over how we can enhance our code base by using <em>generics</em><strong> </strong>instead of ignoring the types by using <em>any</em>.</p><p>If you are experienced with server-side languages, such as C#, Java, etc., you would already have an understanding or at least been introduced to how it works.</p><p>Take, for example, the function below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d250710e6a53631ef1a75e2ce7132723/href">https://medium.com/media/d250710e6a53631ef1a75e2ce7132723/href</a></iframe><p>Now, that is a basic function. Our definition is simply to add two variables.</p><p>If the variables are numeric, it will do a mathematical addition and return the sum. However, if at least one of the variables is a string, it will concatenate<strong> </strong>it and return a string.</p><p>When we hover to get some type of help, we would see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*XgGeaD9pKJVbTkzAKfE6og.png" /></figure><p>By default, TypeScript types variables as any because every variable must<strong> </strong>have a type. The type any<em> </em>basically says that, once a variable or function has this type, the compiler should not type-check it.</p><p>Though this can be very tempting to use, I would highly encourage and recommend you not to use it. Of course, there are edge cases where it’s more convenient to use any instead of writing a convoluted type check. However, the first approach is to assign a proper type.</p><p>Now, let’s assume that we want to keep the same function structure but allow the consumer of the function to define which type it should return.</p><p>It’s quite hard to do this, however. Here is what you need to do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/617d86e55904d95f4bfc3d61233d55ea/href">https://medium.com/media/617d86e55904d95f4bfc3d61233d55ea/href</a></iframe><p>Simple, right?</p><p>Now, look at what happens when we hover:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*1DPRLQ4gy8i-Gifn778gpg.png" /></figure><p>As you can see, all we do is define an arbitrary type as R and then tell the function that our return type will be that same R.</p><p>This way, whoever consumes it, can define the return type themselves and it is guaranteed to have that return type after the function has returned!</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*aEajvVTAy8ytA9X8-MAFQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*l6qwTYGM9KQmxh2B20yIIg.png" /></figure><p>As you can see, both use the same function, however, the resulting type<em> </em>is not identical as the consumer has changed the return type without touching the function definition.</p><p><strong>Please Note</strong>: These are not real-world examples and are only used to expose the generic functionality.😅</p><p>It is just the tip of the iceberg! There are many more ways to apply this functionality such as functions, interfaces, classes, keys, objects, etc. This is the power of generics.</p><p>Instead of using any<strong> </strong>and ignoring the type, enforce it and use it to your advantage. This will help you and others that are either reading or consuming your codebase in some way.</p><p>Additionally, it enhances your testing abilities because it was a great way to construct a “meta” function, without changing the definition but having a consumer-defined result type.</p><p>You can learn more about generics by reading the <a href="https://www.typescriptlang.org/docs/handbook/generics.html">TypeScript Hand Book</a>.<br>I hope this introduction highlights one of TypeScript’s many features, used to amplify JavaScript and your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c6543ba88ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drag and Drop Made Easy With RxJS]]></title>
            <link>https://ndcunningham.medium.com/drag-and-drop-made-easy-with-rxjs-8cd4a8994a07?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd4a8994a07</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Thu, 11 Jul 2019 22:16:39 GMT</pubDate>
            <atom:updated>2019-08-22T19:41:28.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick introduction to a popular feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iKuOiX29vDot0MTwo_lZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jackjross?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jack Ross</a> on <a href="https://unsplash.com/search/photos/dog-sled?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are new to <a href="https://angular.io/guide/rx-library">RxJS</a>, you have been missing out!</p><p>No worries, though. Now is a great opportunity to start getting involved. In this piece, you will learn how easy it is to create a drag and drop for any element.</p><p>I won’t go in-depth about RxJS today. I just wanted to make something quickly, as this feature is regularly requested.</p><p>Let’s begin with the element which you would like to be dragged.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7fd99d67719658f4709a7035778ad5e/href">https://medium.com/media/a7fd99d67719658f4709a7035778ad5e/href</a></iframe><p>Now that we have the element set up, it is time to wire up the JavaScript/TypeScript. I will be using TypeScript, however the same can be applied using JavaScript.</p><p>First, we should find the element we would like to drag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ffc77cdaec2bae536a2bfb7c76c65f5/href">https://medium.com/media/7ffc77cdaec2bae536a2bfb7c76c65f5/href</a></iframe><p>Now for the easy part — getting RxJS to handle our streams. These are what we are considering:</p><ol><li>When the user starts to drag the element.</li><li>When the user is dragging the element.</li><li>When the user has dropped the element.</li></ol><p>This is how we would do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47660cf2ccd54c028bcc96d31d3f5aa7/href">https://medium.com/media/47660cf2ccd54c028bcc96d31d3f5aa7/href</a></iframe><p>I used document for our target on mousemove, because the user has the option of moving the mouse outside of our application. I still want to be able to track it so that when they re-enter, the box will still be moving.</p><p>There are many ways to handle this, but for this example, I will use this approach.</p><h4>Drag me</h4><p>Now, we have our element to drag and the events which we are interested in all wired up. Let’s compose a drag Observable to push out the positions so that we can change/animate the movement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440a43bf85186505565d0ca8492813fa/href">https://medium.com/media/440a43bf85186505565d0ca8492813fa/href</a></iframe><p>If you understand what’s going on here, that’s great! Look how easy that is!<br>I’ll try to explain so that everyone can understand.</p><p>What we are doing here is composing the observables. This means I am combining them in such a way that we get values when we need to.</p><p>We start off with, as that will tell us when to start tracking for the positions. I’ll explain the switchMap later. Inside that flattening operator (unwrap the observable and return the value) we are subscribing to mousemove$ because I want all the values (positions) while the user is moving the mouse after they have mousedown$.</p><p>To find where the box should be moved to, simply find the delta between the starting mousedown and the current position of the mouse given by mousemove$. For further reading, check out <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/offsetX">OffsetX</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX">ClientX</a>.</p><p>Next, we have a takeUntil and we bind it to mouseup$. This keeps streaming all the events from mousemove$, and, when the user releases the mouse (i.e. mouseUp), it stops tracking the mouse move event.</p><p>This is a big benefit to using RxJS since you can actively compose streams in different ways all towards your specific use case.</p><p>Lastly, we should subscribe and apply the deltas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3fda5ce6eab774a9b3e080482a769ee/href">https://medium.com/media/c3fda5ce6eab774a9b3e080482a769ee/href</a></iframe><p>That’s all!</p><p>See it in action!</p><p>By the way, in the stackblitz, there is a little Easter egg. See if you can find and understand it. If you don’t, just research!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdrag-and-drop-rx%3Fembed%3D1%26file%3Dindex.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdrag-and-drop-rx%3Fembed%3D1%26file%3Dindex.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.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/63ff319ef5c2a82217638fbd47ed892f/href">https://medium.com/media/63ff319ef5c2a82217638fbd47ed892f/href</a></iframe><p>Keep on sharing the knowledge. It will only make us stronger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd4a8994a07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular, Typescript, and Decorators]]></title>
            <link>https://ndcunningham.medium.com/angular-typescript-and-decorators-2f58707796d7?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f58707796d7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[decorators]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Fri, 05 Jul 2019 16:54:23 GMT</pubDate>
            <atom:updated>2019-08-22T19:44:15.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>Consider using the unsung feature of decorators to power-up your angular web application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KAD7YGFnhNaz9_SN" /></figure><p>In this post, we’ll learn what decorators are, why they’re useful, and how to create them. We’ll do this with TypeScript — demonstrating how useful this is in the angular framework.</p><h3>Decorators???</h3><p>In truth, <em>decorators </em>are not a part of ES6. However, in keeping with the nature of TypeScript they’re currently an experimental feature, which can be enabled by adding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/331ea7e25c8b1e8cd9429a3d2c9c48f0/href">https://medium.com/media/331ea7e25c8b1e8cd9429a3d2c9c48f0/href</a></iframe><p>If you need more details about the draft, head over to the <a href="https://github.com/tc39/proposal-decorators">TC39 proposal for decorators</a>.</p><h4>OK, and…???</h4><p>Hold on! I just want to make it clear that decorators are not a part of TypeScript by default and <em>certainly</em> not a part of JavaScript as of yet.</p><blockquote>A <em>Decorator</em> is a special kind of declaration that can be attached to a <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators">class declaration</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators">method</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#accessor-decorators">accessor</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#property-decorators">property</a>, or <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators">parameter</a>.</blockquote><p>One quick point is to include emitDecoratorMetadata for your compiler options. You would use this in conjunction with experimentalDecorators for design-time type information to be exposed at runtime. It’s similar to Reflect in C#.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/202bb408cdb1b438078a881fd580be62/href">https://medium.com/media/202bb408cdb1b438078a881fd580be62/href</a></iframe><h4>Now back to business</h4><p>Decorators allow you to modify/adjust classes and functions by annotating i.e. <em>decorating with your custom super-powered function.</em></p><p>They’re not a new thing to the programming world — Java and C# and other backend focused programming language already have them. The feature is similar to function overloading and overriding.</p><p>However in JavaScript, this has not been the case — and there is always excitement for new cool and shiny things!</p><h3>Usefulness</h3><p>If you are an Angular developer, you may have noticed that decorators are the backbone, and what has given rise to the Angular framework. <br>It is a “decorators + typescript = angular” sort of thing.</p><p>Angular uses decorators for many many things and even “<em>third party</em>”<em> </em>libraries like NgRx. Things you may or may not have seen include, but are not limited to:</p><ul><li>@Component</li><li>@Injectable</li><li>@Directive</li><li>@NgModule</li><li>@Effect</li></ul><p>Not to throw shade on vanilla JS, but it is completely doable to do the same however it is frankly painful. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e17c27eea90d1dd50da99abb1377f37/href">https://medium.com/media/9e17c27eea90d1dd50da99abb1377f37/href</a></iframe><p>vs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/922839861fe0bc9759baf395381e22aa/href">https://medium.com/media/922839861fe0bc9759baf395381e22aa/href</a></iframe><p>The @Component is the decorator piece, which modifies the class so that it can take additional parameters such as a template and selector. You can also see the difference with the length, encapsulation, and wordiness.</p><p>Let’s say we have a vehicle class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6e06f6ab4b5e9a3d8477719472691c5/href">https://medium.com/media/b6e06f6ab4b5e9a3d8477719472691c5/href</a></iframe><p>Instead of creating subclasses (most OOP would do this) to define a bike, you could create a decorator to define these!</p><h4>Demo</h4><p>If we want to annotate class members then we would have to annotate them individually.</p><blockquote>A <em>Class Decorator</em> is declared just before a class declaration. The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition. A class decorator cannot be used in a declaration file, or in any other ambient context (such as on a <em>declare</em> class).</blockquote><p>I want to be able to freeze any class I add my decorator too, this way it will not allow mutations to the class or its prototype. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b68f3c5ef96e67c249f3da9c0b2e6065/href">https://medium.com/media/b68f3c5ef96e67c249f3da9c0b2e6065/href</a></iframe><p>Now to apply the decorator is simply will freeze the class when it is <em>declared</em>. So to test this we can simply:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ac6174191dba82498ca308b16232ce/href">https://medium.com/media/c4ac6174191dba82498ca308b16232ce/href</a></iframe><h4>What about modifying what the constructor does?</h4><blockquote>If the class decorator returns a value, it will replace the class declaration with the provided constructor function.<br>Should you choose to return a new constructor function, you must take care to maintain the original prototype. The logic that applies decorators at runtime will not do this for you.</blockquote><p>Let’s see how we could implement this. First, we have to adjust our decorator definition and implementation. This is how typescript.lang define theirs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e50f3d40b9378937d98503057268f189/href">https://medium.com/media/e50f3d40b9378937d98503057268f189/href</a></iframe><p>However, in our scenario we can make it slightly more readable with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdedaaa5a04d89e3421394eebb38ca45/href">https://medium.com/media/cdedaaa5a04d89e3421394eebb38ca45/href</a></iframe><p>The declaration is stating a few things:</p><ol><li>We would like to extend the current/incoming class.</li><li>T is extending the prototype of the current class.</li></ol><p>When you hover over T we’ll see:</p><pre>(type parameter) T in bike&lt;T extends new (...args: any[]) =&gt; {}&gt;(vehicle: T): {<br>    new (...args: any[]): (Anonymous class);<br>    prototype: bike&lt;any&gt;.(Anonymous class);<br>} &amp; T</pre><p>As you can see, the returned declaration for T includes our decorator.</p><p>Now to augment the current vehicle, which is easily done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d484481fa9934fa199f14aee1c22e72f/href">https://medium.com/media/d484481fa9934fa199f14aee1c22e72f/href</a></iframe><p>Easy, peasy, lemon squeezy!</p><p>This example was just to show how to use decorators to augment your classes. I am by no means saying that if you have a vehicle class you <em>should </em>use a decorator to do these things. They’re more useful for things which are done repeatedly.</p><h3>Finally</h3><p>Let’s try to add some parameters to make it more configurable.</p><p>Our bike will only be defined as a two-wheeler, but we could customize or add configurations for n number of params:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e54113ef0e4c47749cb5111b3178cd2/href">https://medium.com/media/5e54113ef0e4c47749cb5111b3178cd2/href</a></iframe><p>This will allow the consumer of this decorator to define the properties for the class rather than closing it off. Additionally, it makes it much easier to test with multiple configs.</p><p>One scenario where we could use this is in having our own translation logic for each component.</p><p><em>That’s it!</em></p><p>Decorators can change how we design and develop our applications. They promote encapsulation and offers flexibility when needed. The next time you run into a problem involving features for multiple classes, functions or members, you have the knowledge to will help you make the decision easier!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f58707796d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading for Images… So Easy]]></title>
            <link>https://ndcunningham.medium.com/lazy-loading-for-images-so-easy-8dd7739a5e47?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd7739a5e47</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 22:51:13 GMT</pubDate>
            <atom:updated>2020-08-30T15:41:25.216Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to defer loading for increased performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nO4fp7rKeUVNHKRpI4oW8A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brunocervera?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">BRUNO CERVERA</a> on <a href="https://unsplash.com/search/photos/laptop-in-bed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is a pretty quick post about <a href="https://angular.io/">Angular</a> directives and how to use some new browser APIs to achieve them.</p><p>These can also can be used outside of Angular. The code isn’t too attached to a framework because the underlying functionality is really just JavaScript.</p><p>In this current environment, applications need to load fast and have many assets (images, fonts, translations, etc.). Performance is on everyone’s mind, or at least most people’s.</p><p>One technique to achieve this is to use <em>lazy loading</em>.</p><p>Lazy loading is a technique that defers the loading of non-critical resources while the page is initially loading. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, “non-critical” is often synonymous with “off-screen.”</p><p><a href="https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/">Lazy Loading Images and Video | Web Fundamentals | Google Developers</a></p><p>In a much simpler form, it allows you to load resources that are not needed until necessary or at a point in time where the application is idle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ff42352094ce221bbf04c9dfc8cc20a/href">https://medium.com/media/4ff42352094ce221bbf04c9dfc8cc20a/href</a></iframe><p>Let’s say we have 500 images (an exaggeration). So, items is an array of length 500.<em> </em>If each image is 1mb in size (another exaggeration)️, we would hypothetically load 500mb worth of data, even though the user will see four to five at a time, at most.</p><h3><strong>The Solution</strong></h3><p>One way to deal with this problem is to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer API</a>.</p><blockquote>The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.</blockquote><p>This just means that it provides a way to allow developers to know when an element is currently being viewed (can be seen).</p><p>One way to allow this to be shared, but modular, is to create a directive:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/356115c336e602925b8d50f00dd2ba25/href">https://medium.com/media/356115c336e602925b8d50f00dd2ba25/href</a></iframe><p>All this does is create an intersection observer on the element. Then we utilize the entry.isIntersecting property, which does a lot of the heavy lifting. It’s created this way for brevity. Read more about the API in the previous link.</p><p>Then, let&#39;s add the directive into our image element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad781c471d6c590f09ccbdcc28d33e28/href">https://medium.com/media/ad781c471d6c590f09ccbdcc28d33e28/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odd3Qd2q-woM6DhCUfscOw.png" /><figcaption>After using the directive</figcaption></figure><p>As you can see, the image that is currently being shown has an src attribute, but the one below it doesn’t. If we scroll it into view, the intersection object will notify the directive and the directive will apply the src to it.</p><p>And that’s it! Easy.</p><p>The <a href="https://www.npmjs.com/package/ngx-lazy-image">package</a> is available on npm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd7739a5e47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Form Race Conditions in Angular With RxJS]]></title>
            <link>https://ndcunningham.medium.com/handling-angular-forms-race-conditions-with-rxjs-b4e31bb73ba0?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e31bb73ba0</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 07:13:35 GMT</pubDate>
            <atom:updated>2019-08-14T00:14:09.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Highlighting a common scenario in Angular when using forms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDu4SPHYSOIunz8bLvsuMQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@szolkin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sergey Zolkin</a> on <a href="https://unsplash.com/search/photos/online-form?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is part 1 of 3 where we highlight a common scenario in <a href="https://angular.io/">Angular</a> when we use forms, especially with autosaving.</p><ul><li>Part 1: Highlight the situation and handle it with <a href="https://www.learnrxjs.io/">RxJS</a>.</li><li>Part 2: Enhance with <a href="https://ngrx.io/">NgRx</a>.</li><li>Part 3: Compartmentalize and simplify with <a href="https://nx.dev/angular/guides/misc-data-persistence">Nx</a>.</li></ul><p>Now, this will only highlight a very minimal use case, using ngModel<strong>, </strong>but it can be applied to very complex forms for both reactive<strong> </strong>and template-driven forms.</p><h3>The Situation</h3><p>Let’s say we have a text area for comments and a button that goes to a different page to view all your comments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d53540a8c4f65d0a39e974d7baa9be8c/href">https://medium.com/media/d53540a8c4f65d0a39e974d7baa9be8c/href</a></iframe><p>The comments get updated when the textarea fires a blur event. This means that when the user focuses on another element, we will save the current textarea value.</p><p>This is a naive approach to an auto-save feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a48750dd2f5b97211fd1bb9a7c729b4f/href">https://medium.com/media/a48750dd2f5b97211fd1bb9a7c729b4f/href</a></iframe><p>If you realize what will happen at this stage, kudos!</p><p>If not, keep reading.</p><p>Developers often assume that clients will experience the same speed and response time as they do in their development environment.</p><h3>The Problem</h3><p>Why is this a race condition or what’s the problem?</p><p>Let’s assume:</p><ol><li>It takes one to three seconds to save your comments to the database.</li><li>It takes half to one second to retrieve all comments from the database.</li><li>It takes a negligible amount of time to move between both pages.</li></ol><p>Now, if a user types a comment and clicks to go to the next page <em>without </em>intentionally clicking elsewhere to ensure that the comment is saved, more often than not, the user will experience a <strong>race </strong>condition, especially on a cellular network.</p><p>The race condition is when the POST<strong> </strong>call to save<strong> </strong>the newly created comment is still in-flight,<strong> </strong>while the user is on the second page viewing the comments.</p><p>In a normal development environment, this <em>may </em>work as expected. Moreover, this is usually found late in the development cycle mixed with complex business logic, etc.</p><h3>Handling Race Conditions</h3><p>Now, there are many ways to handle this, with or without RxJS.</p><p>However, this approach will use RxJS as it is very prevalent in the Angular ecosystem. Its API has a symbiotic relationship with what we want to achieve.</p><p>Which API am I talking about? Well, we will use a mixture of <a href="https://rxjs-dev.firebaseapp.com/api/index/function/fromEvent">fromEvent</a>, <a href="https://rxjs-dev.firebaseapp.com/api/index/function/defer">defer</a>, <a href="https://rxjs-dev.firebaseapp.com/api/operators/delay">delay</a>, <a href="https://rxjs-dev.firebaseapp.com/api/operators/mapTo">mapTo</a>, and the <a href="https://rxjs-dev.firebaseapp.com/api/operators/concatMap">concatMap </a>operator, just to name a few.</p><p>If you are new to RxJS, I suggest reading material from these great authors:</p><ul><li><a href="https://netbasal.com/whos-afraid-of-observables-bde0dc4f48cc">Netanel Basal</a></li><li><a href="https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87">Ben Lesh</a></li></ul><h3>Operator Explanation</h3><p>We use the FromEvent operator to have a handle on our textarea’s blur event so that we can call our saveComment function from inside the component file.</p><p>We also use the FromEvent operator to handle the click event from our button.</p><p>We use defer because the fromEvent operator is eager and makes the observable hot. We do this so that when the component loads, our template reference has not been initialized. There will be an error because it will be undefined.</p><p>When we subscribe inside the ngAfterViewInit, our reference will be available and defer allows us to do this.</p><p>So, in short, defer makes a hot observable cold.</p><p>We use delay because we want to ensure that our specified event runs first if they are both fired. This will become clearer when you see the implementation.</p><p>We use mapTo to differentiate between events so we know how to handle them further down the operator chain.</p><p>Now, the concatMap operator basically allows you to pause all incoming requests while a previous request is still active.</p><h3>Update</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b48ca0212e1f05098d9ba19ebc6ba8f/href">https://medium.com/media/7b48ca0212e1f05098d9ba19ebc6ba8f/href</a></iframe><p>We have made a few changes to the template. As I explained earlier, we will now handle the events inside our component, instead of hooking them from the template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/430db339b69ec369f4618f60e47d7275/href">https://medium.com/media/430db339b69ec369f4618f60e47d7275/href</a></iframe><p>Then, we combine the observables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67e9791523d4876223e36bc65242c858/href">https://medium.com/media/67e9791523d4876223e36bc65242c858/href</a></iframe><h3>Play-by-Play</h3><p>There are a few changes from what we had before. Indeed, now our template looks cleaner.</p><p>So, what’s really happening?</p><p>When our textarea has fired its blur event, it should behave as before.</p><p>It will:</p><ol><li>Now be called from an observable.</li><li>The mapTo will change it to A so that the concatMap operator knows how to handle it; it’s like an identifier.</li></ol><p>Additionally…</p><p>If the blur event fires and the click event fires, such as when a user types into the text area and immediately clicks on the button, it will cause this scenario.</p><p>Instead of hoping that the blur event sequence finishes in time so that, when the user navigates, they see the updated list, we now:</p><ol><li>Ensure that, if they are both called, the click call will wait for 50 ms before continuing.</li><li>While the click call is waiting for the blur, the call will go through to the concatMap.</li><li>When the click call has finished waiting and wants to enter the concatMap while the blur event is still in flight, it will wait until it’s finished before it can navigate, as is the nature of concatMap.</li></ol><h3>Full Solution</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95f46ef1959d0db5dc13067c860b724b/href">https://medium.com/media/95f46ef1959d0db5dc13067c860b724b/href</a></iframe><h3>Important</h3><p>Though it may seem like I use a long list of operators, it’s important to know that this is an ad-hoc method which would have to be repeated for each of these inside of your application.</p><p>Stay tuned to where we update this solution using NgRx.</p><p>I have a <a href="https://stackblitz.com/">StackBlitz</a> example coming soon as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e31bb73ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Completing/Unsubscribing Your Observable Stream Is Important]]></title>
            <link>https://ndcunningham.medium.com/why-completing-unsubscribing-your-observable-stream-is-important-f96b513e83c1?source=rss-929862e54c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96b513e83c1</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nicholas Cunningham]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 02:15:52 GMT</pubDate>
            <atom:updated>2019-09-14T00:32:44.931Z</atom:updated>
            <content:encoded><![CDATA[<h4>Observables are really powerful as they offer a great opportunity for handling async functionality in a succinct manner</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*L80j1JSHvjIrFABZ" /><figcaption>Photo by <a href="https://unsplash.com/@mattbotsford">Matt Botsford</a> at <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote>“With <strong>great power</strong> comes <strong>great responsibility.</strong>” –Amazing Fantasy #15</blockquote><p>A very important part in RxJS is to ensure that your observables have a shelf life and that they are deterministic. They should not live on forever or else they’re a potential risk for a memory leak.</p><p>The example below highlights how having a service that returns data over a period of time seems to work fine on the surface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5729ce524777065ead315b78fa363a00/href">https://medium.com/media/5729ce524777065ead315b78fa363a00/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fce12a0401e3051cb682f7616751b203/href">https://medium.com/media/fce12a0401e3051cb682f7616751b203/href</a></iframe><p>Component One has a service that is subscribed to on the template and has navigation to Component Two.</p><p>Component Two navigates back to Component One.</p><p>No problem, right?</p><h3><strong>Wrong — Take a Closer Look</strong></h3><p>When Component One navigates to Component Two the <a href="http://reactivex.io/rxjs/class/es6/Subscription.js~Subscription.html">subscription </a>(a reference to that observable) is still there. So when the user navigates back to Component One, guess what happens?</p><p>Another subscription has started alongside the previous one.</p><p>Check out that StackBlitz and keep an 👀 on the console while navigating back and forth from Component One and Component Two.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-hwfqfb%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-hwfqfb%3Ffile%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.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/c9f0c76c4e46dd942bede5d5b6341e3b/href">https://medium.com/media/c9f0c76c4e46dd942bede5d5b6341e3b/href</a></iframe><p>This is a very common scenario in Angular where the developer binds data inside the ngOnInit to their local variable and the stream periodically gives data.</p><p>Imagine having multiple of these across multiple components on a single page. It can get out of hand pretty fast 🌋 🏃</p><h3>How Do We Handle This?</h3><p>Well, there are multiple ways to handle this use case. One way is to use angular <a href="https://angular.io/api/common/AsyncPipe">async pipe</a><em>. </em>What that really does is, if your component has been destroyed, it will unsubscribe or clean up your stream.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-u7q8oy%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.html&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-u7q8oy%3Ffile%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.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/6e93f7ebea085d96fe63f5f543b66b18/href">https://medium.com/media/6e93f7ebea085d96fe63f5f543b66b18/href</a></iframe><h4>But I am not using that data on my template, the async pipe does not work for me…</h4><p>You can also use a completion observable such as an AsyncSubject with the takeUntil operator.</p><p>Now, without going into too many details, an AsyncSubjectis a subject (observable and observer) where only the last value of the observable execution is sent to its subscribers and only when the execution completes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ngvuzu%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ngvuzu%3Ffile%3Dsrc%252Fapp%252Fcomponent-one%252Fcomponent-one.component.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.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/c24c0332b6892f307f73d61f457c3eef/href">https://medium.com/media/c24c0332b6892f307f73d61f457c3eef/href</a></iframe><p>You could also use take(n), where n is the amount of times you expect to receive data before navigating.</p><p>Gotcha.<strong> </strong>With this scenario take(n) if the n is not reached before the user navigates, you will fall into the same scenario where the subscription is still active and continues counting from where it left off.</p><h3>Conclusion</h3><p>With using either the async pipe or using a Subject, these two strategies should cover most of your scenarios where your observable streams should complete.</p><p>Want to dive deeper here? Some useful and influential people are below:</p><p><a href="https://netbasal.com/@NetanelBasal?source=post_header_lockup">Netanel Basal</a><a href="https://netbasal.com/rxjs-subjects-for-human-beings-7807818d4e4d">’s — Subject</a></p><p><a href="https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87">Ben Lesh’s — Don’t Unsubscribe so much</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96b513e83c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>