<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ RxJS - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ RxJS - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 27 Jul 2026 10:32:17 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/rxjs/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Understand RxJS Operators by Eating a Pizza: zip, forkJoin, & combineLatest Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Samuel Teboul What is RxJS? Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change - Wikipedia RxJS is a library for reactive programming using observables that makes it easier to co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understand-rxjs-operators-by-eating-a-pizza/</link>
                <guid isPermaLink="false">66d460eef855545810e934d5</guid>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 13 May 2020 18:44:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/download.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Samuel Teboul</p>
<h1 id="heading-what-is-rxjs">What is RxJS?</h1>
<blockquote>
<p><em>Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change</em> - <strong>Wikipedia</strong></p>
<p>RxJS is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code - <strong>RxJS docs</strong></p>
</blockquote>
<p>The essential concepts in RxJS are</p>
<ul>
<li><strong>An Observable</strong> is a stream of data</li>
<li><p><strong>Observers</strong> can register up to 3 callbacks:</p>
</li>
<li><p><em>next</em> is called 1:M time to push new values to the observer</p>
</li>
<li><em>error</em> is called at most 1 time when an error occurred</li>
<li><p><em>complete</em> is called at most 1 time on completion</p>
</li>
<li><p><strong>Subscription</strong> "kicks off" the observable stream</p>
</li>
</ul>
<p>Without subscribing the stream won't start emitting values. This is what we call a <strong>cold</strong> <strong>observable.</strong> </p>
<p>It's similar to subscribing to a newspaper or magazine... you won't start getting them until you subscribe. Then, it creates a 1 to 1 relationship between the producer (observable) and the consumer (observer).</p>
<p><img src="https://lh3.googleusercontent.com/_ro6f-oBp5o-e98sRUYOhfC6T_j79UOqNyfzLse5MfSs4WItSaYoHHK6TS7MlN1O5pSZsN98hA6af6L0j_MHh5F7bL8_Vm3fiya9Vw3Xwr4E0DI9IijKqN6VivRX__bkw7ze30EnzjY" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-what-are-rxjs-operators">What are RxJS operators?</h1>
<p>Operators are pure functions that enable a functional programming style of dealing with collections with operations. There are two kinds of operators:</p>
<ul>
<li>Creation operators</li>
<li>Pipeable operators: transformation, filtering, rate limiting, flattening</li>
</ul>
<p>Subjects are a special type of Observable that allows values to be <strong>multicast</strong> to many Observers. While plain Observables are <strong>unicast</strong> (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. This is what we call a <strong>hot</strong> <strong>observable.</strong></p>
<p>In this article, I will focus on the <code>zip</code>, <code>combineLatest</code> and <code>forkJoin</code> operators. These are RxJS combination operators, which means that they enable us to join information from multiple observables. Order, time, and structure of emitted values are the primary differences among them.</p>
<p>Let's look at each one individually.</p>
<h1 id="heading-zip">zip()</h1>
<ul>
<li><code>zip</code> doesn’t start to emit until each inner observable emits at least one value</li>
<li><code>zip</code> emits as long as emitted values can be collected from all inner observables</li>
<li><code>zip</code> emits values as an array</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_oY4pB5RbNeloyauM1tpWmg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let’s imagine that you are with Mario and Luigi, two of your best friends, at the best Italian restaurant in Rome. Each one of you orders a drink, a pizza, and a dessert. You specify to the waiter to bring the drinks first, then the pizzas, and finally the desserts.</p>
<p>This situation can be represented with 3 different observables, representing the 3 different orders. In this specific situation, the waiter can use the <code>zip</code> operator to bring (emit) the different order items by category.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_ve5RtSu2eH7b3pe8lJQ9rg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<p>If you go back to the same Italian restaurant with your girlfriend, but she doesn’t want to eat, this is what will happen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_8g5NLq3fTBekvu6gvnfJcw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the <code>waiter$</code> uses the <code>zip</code> operator, you will only get your drink!</p>
<p>Why?</p>
<p>Because, when the <code>waiter$</code> emits the drinks, the <code>girlfriend$</code> observable is complete and no more value can be collected from it. Hopefully, the <code>waiter$</code> can use another operator for us so we don't break up with our girlfriend ?</p>
<h1 id="heading-combinelatest">combineLatest()</h1>
<ul>
<li><code>combineLatest</code> doesn’t start to emit until each inner observable emits at least one value</li>
<li>When any inner observable emits a value, emit the last emitted value from each</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_TrJG2NP6PgA0HJMj598lpQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At the exact same restaurant, the smart <code>waiter$</code> now decide to use <code>combineLatest</code> operator.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_GHNM2srLwN4Wihm7U8bcQg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<p>With <code>combineLatest</code>, the <strong>order</strong> of the provided inner observables does matter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If <code>you$</code> is provided first to <code>waiter$</code>, it will emit only one value <code>["Tiramisu", "Sprite"]</code>. </p>
<p>This is happening because <code>combineLatest</code> doesn’t start to emit until each inner observable emits at least one value. <code>girlfriend$</code> starts emitting when the first inner observable emits its last value. Then, <code>combineLatest</code> emits the last values collected from both inner observables.</p>
<h1 id="heading-forkjoin">forkJoin()</h1>
<ul>
<li><code>forkJoin</code> emits the last emitted value from each inner observables after they <strong>all</strong> complete</li>
<li><code>forkJoin</code> will never emit if one of the observables doesn’t complete</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_O-Uis5OrgaeUrh6JSgHkTg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When you go to the restaurant and order for a pizza, you don’t want to know all the steps about how the pizza is prepared. If the cheese is added before the tomatoes or the opposite. You just want to get your pizza! This is where <code>forkJoin</code> comes into play.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_tB1kiVeQ2kpicnNjFnN_dA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<ul>
<li>If one of the inner observables throws an error, all values are lost</li>
<li><code>forkJoin</code> doesn’t complete</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_zLaN2lzWlASOC3X7f-k3kA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>If you are only concerned when <strong>all</strong> inner observables complete successfully, you can catch the error from the <strong>outside</strong></li>
<li>Then, <code>forkJoin</code> completes</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>If you don’t care that inner observables complete successfully or not, you must catch errors from every single inner observable</li>
<li>Then, <code>forkJoin</code> completes</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Personally, when I go to a restaurant with friends, I don’t care if one of them receives a burnt pizza. I just want mine ? so I will ask the <code>waiter$</code> to catch the errors from inner observables individually.</p>
<h1 id="heading-wrap-up">Wrap up</h1>
<p>We covered a lot in this article! Good examples are important to better understand RxJS operators and how to choose them wisely. </p>
<p>For combination operators like <code>zip</code>, <code>combineLatest</code>, and <code>forkJoin</code> the order of inner observables that you provide is also critical, as it can drives you to unexpected behaviours.</p>
<p>There is much more to cover within RxJS and I will do it in further articles.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_RHYpi9BEvKatE0NRsHfnOw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I hope you enjoyed this article! ?</p>
<p>? You can <a target="_blank" href="https://twitter.com/tSamoss">follow me on Twitter</a> to get notified about new Angular/RxJS blog posts and cool tips!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Beginner's Guide to RxJS & Redux Observable ]]>
                </title>
                <description>
                    <![CDATA[ By Praveen Redux-Observable is an RxJS-based middleware for Redux that allows developers to work with async actions. It's an alternative to redux-thunk and redux-saga. This article covers the basics of RxJS, how to setup Redux-Observables, and some o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/beginners-guide-to-rxjs-redux-observables/</link>
                <guid isPermaLink="false">66d46089264384a65d5a95c3</guid>
                
                    <category>
                        <![CDATA[ observables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 12 Mar 2020 23:28:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/IMG_20181012_232217-min-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Praveen</p>
<p><a target="_blank" href="https://github.com/redux-observable/redux-observable/">Redux-Observable</a> is an RxJS-based middleware for Redux that allows developers to work with async actions. It's an alternative to redux-thunk and redux-saga.</p>
<p>This article covers the basics of RxJS, how to setup Redux-Observables, and some of its practical use-cases. But before that, we need to understand the <em>Observer Pattern</em>.</p>
<h2 id="heading-observer-pattern">Observer Pattern</h2>
<p>In Observer pattern, an object called "Observable" or "Subject", maintains a collection of subscribers called "Observers." When the subjects' state changes, it notifies all its Observers.</p>
<p>In JavaScript, the simplest example would be event emitters and event handlers.</p>
<p>When you do <code>.addEventListener</code>, you are pushing an observer into the subject's collection of observers. Whenever the event happens, the subject notifies all the observers.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/observer-pattern.png" alt="Image" width="600" height="400" loading="lazy">
<em>Observer Pattern</em></p>
<h2 id="heading-rxjs">RxJS</h2>
<p>As per the official website,</p>
<blockquote>
<p><em>RxJS is JavaScript implementation of <a target="_blank" href="http://reactivex.io/">ReactiveX</a>, a library for composing asynchronous and event-based programs by using observable sequences.</em></p>
</blockquote>
<p>In simple terms, RxJS is an implementation of the Observer pattern. It also extends the Observer pattern by providing operators that allow us to compose Observables and Subjects in a declarative manner.</p>
<p>Observers, Observables, Operators, and Subjects are the building blocks of RxJS. So let's look at each one in more detail now.</p>
<h3 id="heading-observers">Observers</h3>
<p>Observers are objects that can subscribe to Observables and Subjects. After subscribing, they can receive notifications of three types - next, error, and complete.</p>
<p>Any object with the following structure can be used as an Observer. </p>
<pre><code class="lang-javascript">interface Observer&lt;T&gt; {
    closed?: boolean;
    next: <span class="hljs-function">(<span class="hljs-params">value: T</span>) =&gt;</span> <span class="hljs-keyword">void</span>;
    error: <span class="hljs-function">(<span class="hljs-params">err: any</span>) =&gt;</span> <span class="hljs-keyword">void</span>;
    complete: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">void</span>;
}
</code></pre>
<p>When the Observable pushes next, error, and complete notifications, the Observer's <code>.next</code>, <code>.error</code>, and <code>.complete</code> methods are invoked.</p>
<h3 id="heading-observables">Observables</h3>
<p>Observables are objects that can emit data over a period of time. It can be represented using the "marble diagram".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/observable-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Successfully completed Observable</em></p>
<p>Where the horizontal line represents the time, the circular nodes represent the data emitted by the Observable, and the vertical line indicates that the Observable has completed successfully.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/observable-with-error.png" alt="Image" width="600" height="400" loading="lazy">
<em>Observable with an error</em></p>
<p>Observables may encounter an error. The cross represents the error emitted by the Observable.</p>
<p>The "completed" and "error" states are final. That means, Observables cannot emit any data after completing successfully or encountering an error. </p>
<h3 id="heading-creating-an-observable">Creating an Observable</h3>
<p>Observables are created using the <code>new Observable</code> constructor that takes one argument - the subscribe function. Observables can also be created using some operators, but we will talk about that later when we talk about Operators.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function"><span class="hljs-params">subscriber</span> =&gt;</span> {
   <span class="hljs-comment">// Subscribe function </span>
});
</code></pre>
<h3 id="heading-subscribing-to-an-observable">Subscribing to an Observable</h3>
<p>Observables can be subscribed using their <code>.subscribe</code> method and passing an Observer.</p>
<pre><code class="lang-javascript">observable.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">error</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">complete</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'completed'</span>);
});
</code></pre>
<h3 id="heading-execution-of-an-observable">Execution of an Observable</h3>
<p>The subscribe function that we passed to the <code>new Observable</code> constructor is executed every time the Observable is subscribed. </p>
<p>The subscribe function takes one argument - the Subscriber. The Subscriber resembles the structure of an Observer, and it has the same 3 methods: <code>.next</code>, <code>.error</code>, and <code>.complete</code>.</p>
<p>Observables can push data to the Observer using the <code>.next</code> method. If the Observable has completed successfully, it can notify the Observer using the <code>.complete</code> method. If the Observable has encountered an error, it can push the error to the Observer using the <code>.error</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create an Observable</span>
<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function"><span class="hljs-params">subscriber</span> =&gt;</span> {
   subscriber.next(<span class="hljs-string">'first data'</span>);
   subscriber.next(<span class="hljs-string">'second data'</span>);
   <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
       subscriber.next(<span class="hljs-string">'after 1 second - last data'</span>);
       subscriber.complete();
       subscriber.next(<span class="hljs-string">'data after completion'</span>); <span class="hljs-comment">// &lt;-- ignored</span>
   }, <span class="hljs-number">1000</span>);
   subscriber.next(<span class="hljs-string">'third data'</span>);
});

<span class="hljs-comment">// Subscribe to the Observable</span>
observable.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">error</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">complete</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'completed'</span>)
});

<span class="hljs-comment">// Outputs:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// first data</span>
<span class="hljs-comment">// second data</span>
<span class="hljs-comment">// third data</span>
<span class="hljs-comment">// after 1 second - last data</span>
<span class="hljs-comment">// completed</span>
</code></pre>
<h3 id="heading-observables-are-unicast">Observables are Unicast</h3>
<p>Observables are <em>unicast</em>, which means Observables can have at most one subscriber. When an Observer subscribes to an Observable, it gets a copy of the Observable that has its own execution path, making the Observables unicast. </p>
<p>It is like watching a YouTube video. All viewers watch the same video content but, they can be at watching different segments of the video.</p>
<p><strong>Example</strong>: let us create an Observable that emits 1 to 10 over 10 seconds. Then, subscribe to the Observable once immediately, and again after 5 seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create an Observable that emits data every second for 10 seconds</span>
<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function"><span class="hljs-params">subscriber</span> =&gt;</span> {
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
        subscriber.next(count++);

        <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">10</span>) {
            <span class="hljs-built_in">clearInterval</span>(interval);   
        }
    }, <span class="hljs-number">1000</span>);
});

<span class="hljs-comment">// Subscribe to the Observable</span>
observable.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Observer 1: <span class="hljs-subst">${value}</span>`</span>);
    }
});

<span class="hljs-comment">// After 5 seconds subscribe again</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    observable.subscribe({
        <span class="hljs-attr">next</span>: <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Observer 2: <span class="hljs-subst">${value}</span>`</span>);
        }
    });
}, <span class="hljs-number">5000</span>);

<span class="hljs-comment">/* Output

Observer 1: 1
Observer 1: 2
Observer 1: 3
Observer 1: 4
Observer 1: 5
Observer 2: 1
Observer 1: 6
Observer 2: 2
Observer 1: 7
Observer 2: 3
Observer 1: 8
Observer 2: 4
Observer 1: 9
Observer 2: 5
Observer 1: 10
Observer 2: 6
Observer 2: 7
Observer 2: 8
Observer 2: 9
Observer 2: 10

*/</span>
</code></pre>
<p>In the output, you can notice that the second Observer started printing from 1 even though it subscribed after 5 seconds. This happens because the second Observer received a copy of the Observable whose subscribe function was invoked again. This illustrates the unicast behaviour of Observables.</p>
<h2 id="heading-subjects">Subjects</h2>
<p>A Subject is a special type of Observable.</p>
<h3 id="heading-creating-a-subject">Creating a Subject</h3>
<p>A Subject is created using the <code>new Subject</code> constructor.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Subject } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

<span class="hljs-comment">// Create a subject</span>
<span class="hljs-keyword">const</span> subject = <span class="hljs-keyword">new</span> Subject();
</code></pre>
<h3 id="heading-subscribing-to-a-subject">Subscribing to a Subject</h3>
<p>Subscribing to a Subject is similar to subscribing to an Observable: you use the <code>.subscribe</code> method and pass an Observer.</p>
<pre><code class="lang-javascript">subject.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">error</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(x),
    <span class="hljs-attr">complete</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"done"</span>)
});
</code></pre>
<h3 id="heading-execution-of-a-subject">Execution of a Subject</h3>
<p>Unlike Observables, a Subject calls its own <code>.next</code>, <code>.error</code>, and <code>.complete</code> methods to push data to Observers.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Push data to all observers</span>
subject.next(<span class="hljs-string">'first data'</span>);

<span class="hljs-comment">// Push error to all observers</span>
subject.error(<span class="hljs-string">'oops something went wrong'</span>);

<span class="hljs-comment">// Complete</span>
subject.complete(<span class="hljs-string">'done'</span>);
</code></pre>
<h3 id="heading-subjects-are-multicast">Subjects are Multicast</h3>
<p>Subjects are <em>multicast:</em> multiple Observers share the same Subject and its execution path. It means all notifications are broadcasted to all the Observers. It is like watching a live program. All viewers are watching the same segment of the same content at the same time.</p>
<p><strong>Example:</strong> let us create a Subject that emits 1 to 10 over 10 seconds. Then, subscribe to the Observable once immediately, and again after 5 seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create a subject</span>
<span class="hljs-keyword">const</span> subject = <span class="hljs-keyword">new</span> Subject();

<span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    subscriber.next(count++);
    <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">10</span>) {
        <span class="hljs-built_in">clearInterval</span>(interval);
    }
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Subscribe to the subjects</span>
subject.subscribe(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Observer 1: <span class="hljs-subst">${data}</span>`</span>);
});

<span class="hljs-comment">// After 5 seconds subscribe again</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    subject.subscribe(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Observer 2: <span class="hljs-subst">${data}</span>`</span>);
    });
}, <span class="hljs-number">5000</span>);

<span class="hljs-comment">/* OUTPUT

Observer 1: 1
Observer 1: 2
Observer 1: 3
Observer 1: 4
Observer 1: 5
Observer 2: 5
Observer 1: 6
Observer 2: 6
Observer 1: 7
Observer 2: 7
Observer 1: 8
Observer 2: 8
Observer 1: 9
Observer 2: 9
Observer 1: 10
Observer 2: 10

*/</span>
</code></pre>
<p>In the output, you can notice that the second Observer started printing from 5 instead of starting from 1. This happens because the second Observer is sharing the same Subject. Since it subscribed after 5 seconds, the Subject has already finished emitting 1 to 4. This illustrates the multicast behavior of a Subject.</p>
<h3 id="heading-subjects-are-both-observable-and-observer">Subjects are both Observable and Observer</h3>
<p>Subjects have the <code>.next</code>, <code>.error</code> and <code>.complete</code> methods. That means that they follow the structure of Observers. Hence, a Subject can also be used as an Observer and passed to the <code>.subscribe</code> function of Observables or other Subjects.</p>
<p><strong>Example:</strong> let us create an Observable and a Subject. Then subscribe to the Observable using the Subject as an Observer. Finally, subscribe to the Subject. All the values emitted by the Observable will be pushed to the Subject, and the Subject will broadcast the received values to all its Observers.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create an Observable that emits data every second</span>
<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function"><span class="hljs-params">subscriber</span> =&gt;</span> {
   <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>;
   <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
       subscriber.next(count++);

       <span class="hljs-keyword">if</span> (count &gt; <span class="hljs-number">5</span>) {
            <span class="hljs-built_in">clearInterval</span>(interval);   
       }
   }, <span class="hljs-number">1000</span>);
});

<span class="hljs-comment">// Create a subject</span>
<span class="hljs-keyword">const</span> subject = <span class="hljs-keyword">new</span> Subject();

<span class="hljs-comment">// Use the Subject as Observer and subscribe to the Observable</span>
observable.subscribe(subject);

<span class="hljs-comment">// Subscribe to the subject</span>
subject.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(value)
});

<span class="hljs-comment">/* Output

1
2
3
4
5

*/</span>
</code></pre>
<h2 id="heading-operators">Operators</h2>
<p>Operators are what make RxJS useful. Operators are pure functions that return a new Observable. They can be categorized into 2 main categories:</p>
<ol>
<li>Creation Operators</li>
<li>Pipeable Operators</li>
</ol>
<h3 id="heading-creation-operators">Creation Operators</h3>
<p>Creation Operators are functions that can create a new Observable. </p>
<p><strong>Example:</strong> we can create an Observable that emits each element of an array using the <code>from</code> operator.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">from</span>([<span class="hljs-number">2</span>, <span class="hljs-number">30</span>, <span class="hljs-number">5</span>, <span class="hljs-number">22</span>, <span class="hljs-number">60</span>, <span class="hljs-number">1</span>]);

observable.subscribe({
    <span class="hljs-attr">next</span>: <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Received"</span>, value),
    <span class="hljs-attr">error</span>: <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(err),
    <span class="hljs-attr">complete</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"done"</span>)
});

<span class="hljs-comment">/* OUTPUTS

Received 2
Received 30
Received 5
Received 22
Received 60
Received 1
done

*/</span>
</code></pre>
<p>The same can be an Observable using the marble diagram.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/from-operator.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-pipeable-operators">Pipeable Operators</h3>
<p>Pipeable Operators are functions that take an Observable as an input and return a new Observable with modified behavior. </p>
<p><strong>Example:</strong> let's take the Observable that we created using the <code>from</code> operator. Now using this Observable, we can to create a new Observable that emits only numbers greater than 10 using the <code>filter</code> operator.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greaterThanTen = observable.pipe(filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x &gt; <span class="hljs-number">10</span>));

greaterThanTen.subscribe(<span class="hljs-built_in">console</span>.log, <span class="hljs-built_in">console</span>.log, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"completed"</span>));

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// 11</span>
<span class="hljs-comment">// 12</span>
<span class="hljs-comment">// 13</span>
<span class="hljs-comment">// 14</span>
<span class="hljs-comment">// 15</span>
</code></pre>
<p>The same can be represented using the marble diagram.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/filter-operator.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There are many more useful operators out there. You can see the full operators list along with examples on the official RxJS documentation <a target="_blank" href="https://rxjs-dev.firebaseapp.com/guide/operators">here</a>. </p>
<p>It is crucial to understand all the commonly used operators. Here are some operators that I use often:</p>
<ol>
<li><code>mergeMap</code></li>
<li><code>switchMap</code></li>
<li><code>exhaustMap</code></li>
<li><code>map</code></li>
<li><code>catchError</code></li>
<li><code>startWith</code></li>
<li><code>delay</code></li>
<li><code>debounce</code></li>
<li><code>throttle</code></li>
<li><code>interval</code></li>
<li><code>from</code></li>
<li><code>of</code></li>
</ol>
<h2 id="heading-redux-observables">Redux Observables</h2>
<p>As per the official website,</p>
<blockquote>
<p><a target="_blank" href="http://github.com/ReactiveX/RxJS">RxJS</a>-based middleware for <a target="_blank" href="http://github.com/reactjs/redux">Redux</a>. Compose and cancel async actions to create side effects and more.</p>
</blockquote>
<p>In Redux, whenever an action is dispatched, it runs through all the reducer functions and a new state is returned. </p>
<p>Redux-observable takes all these dispatched actions and new states and creates two observables out of it - Actions observable <code>action$</code>, and States observable <code>state$</code>. </p>
<p>Actions observable will emit all the actions that are dispatched using the <code>store.dispatch()</code>. States observable will emit all the new state objects returned by the root reducer.</p>
<h2 id="heading-epics">Epics</h2>
<p>As per the official website,</p>
<blockquote>
<p>It is a function which takes a stream of actions and returns a stream of actions. <strong>Actions in, actions out.</strong></p>
</blockquote>
<p>Epics are functions that can be used to subscribe to Actions and States Observables. Once subscribed, epics will receive the stream of actions and states as input, and it must return a stream of actions as an output. <em><strong>Actions In - Actions Out</strong>.</em></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> someEpic = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> { 
    <span class="hljs-keyword">return</span> action$.pipe( <span class="hljs-comment">// subscribe to actions observable</span>
        map(<span class="hljs-function"><span class="hljs-params">action</span> =&gt;</span> { <span class="hljs-comment">// Receive every action, Actions In</span>
            <span class="hljs-keyword">return</span> someOtherAction(); <span class="hljs-comment">// return an action, Actions Out</span>
        })
    )
}
</code></pre>
<p>It is important to understand that all the actions received in the Epic have already <em>finished running through the reducers</em>.</p>
<p>Inside an Epic, we can use any RxJS observable patterns, and this is what makes redux-observables useful.</p>
<p><strong>Example:</strong> we can use the <code>.filter</code> operator to create a new intermediate observable. Similarly, we can create any number of intermediate observables, but the final output of the final observable must be an action, otherwise an exception will be raised by redux-observable.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sampleEpic = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> action$.pipe(
        filter(<span class="hljs-function"><span class="hljs-params">action</span> =&gt;</span> action.payload.age &gt;= <span class="hljs-number">18</span>), <span class="hljs-comment">// can create intermediate observables and streams</span>
        map(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> above18(value)) <span class="hljs-comment">// where above18 is an action creator</span>
    );
}
</code></pre>
<p>Every action emitted by the Epics are immediately dispatched using the <code>store.dispatch()</code>. </p>
<h2 id="heading-setup">Setup</h2>
<p>First, let's install the dependencies.</p>
<pre><code class="lang-shell">npm install --save rxjs redux-observable
</code></pre>
<p>Create a separate folder named <code>epics</code> to keep all the epics. Create a new file <code>index.js</code> inside the <code>epics</code> folder and combine all the epics using the <code>combineEpics</code> function to create the root epic. Then export the root epic.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { combineEpics } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-observable'</span>;
<span class="hljs-keyword">import</span> { epic1 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./epic1'</span>;
<span class="hljs-keyword">import</span> { epic2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./epic2'</span>;

<span class="hljs-keyword">const</span> epic1 = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> {
 ...   
}

<span class="hljs-keyword">const</span> epic2 = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> {
 ...   
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> combineEpics(epic1, epic2);
</code></pre>
<p>Create an epic middleware using the <code>createEpicMiddleware</code> function and pass it to the <code>createStore</code> Redux function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createEpicMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-observable'</span>;
<span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> rootEpic <span class="hljs-keyword">from</span> <span class="hljs-string">'./rootEpics'</span>;

<span class="hljs-keyword">const</span> epicMiddleware = createEpicMiddlware();

<span class="hljs-keyword">const</span> store = createStore(
    rootReducer,
    applyMiddleware(epicMiddlware)
);
</code></pre>
<p>Finally, pass the root epic to epic middleware's <code>.run</code> method.</p>
<pre><code class="lang-javascript">epicMiddleware.run(rootEpic);
</code></pre>
<h2 id="heading-some-practical-usecases">Some Practical Usecases</h2>
<p>RxJS has a big learning curve, and the redux-observable setup worsens the already painful Redux setup process. All that makes Redux observable look like an overkill. But here are some practical use cases that can change your mind.</p>
<p><em>Throughout this section, I will be comparing redux-observables with redux-thunk to show how redux-observables can be helpful in complex use-cases. I don't hate redux-thunk, I love it, and I use it every day!</em></p>
<h3 id="heading-1-make-api-calls">1. Make API Calls</h3>
<p><strong>Usecase:</strong> Make an API call to fetch comments of a post. Show loaders when the API call is in progress and also handle API errors.</p>
<p>A redux-thunk implementation will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComments</span>(<span class="hljs-params">postId</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">dispatch</span>) =&gt;</span> {
        dispatch(getCommentsInProgress());
        axios.get(<span class="hljs-string">`/v1/api/posts/<span class="hljs-subst">${postId}</span>/comments`</span>).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
            dispatch(getCommentsSuccess(response.data.comments));
        }).catch(<span class="hljs-function">() =&gt;</span> {
            dispatch(getCommentsFailed());
        });
    }
}
</code></pre>
<p>and this is absolutely correct. But the action creator is bloated.</p>
<p>We can write an Epic to implement the same using redux-observables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getCommentsEpic = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> action$.pipe(
    ofType(<span class="hljs-string">'GET_COMMENTS'</span>),
    mergeMap(<span class="hljs-function">(<span class="hljs-params">action</span>) =&gt;</span> <span class="hljs-keyword">from</span>(axios.get(<span class="hljs-string">`/v1/api/posts/<span class="hljs-subst">${action.payload.postId}</span>/comments`</span>).pipe(
        map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> getCommentsSuccess(response.data.comments)),
        catchError(<span class="hljs-function">() =&gt;</span> getCommentsFailed()),
        startWith(getCommentsInProgress())
    )
);
</code></pre>
<p>Now it allows us to have a clean and simple action creator like this,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComments</span>(<span class="hljs-params">postId</span>) </span>{
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">type</span>: <span class="hljs-string">'GET_COMMENTS'</span>,
        <span class="hljs-attr">payload</span>: {
            postId
        }
    }
}
</code></pre>
<h3 id="heading-2-request-debouncing">2. Request Debouncing</h3>
<p><strong>Usecase:</strong> Provide autocompletion for a text field by calling an API whenever the value of the text field changes. API call should be made 1 second after the user has stopped typing.</p>
<p>A redux-thunk implementation will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> timeout;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">valueChanged</span>(<span class="hljs-params">value</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-params">dispatch</span> =&gt;</span> {
        dispatch(loadSuggestionsInProgress());
        dispatch({
            <span class="hljs-attr">type</span>: <span class="hljs-string">'VALUE_CHANGED'</span>,
            <span class="hljs-attr">payload</span>: {
                value
            }
        });

        <span class="hljs-comment">// If changed again within 1 second, cancel the timeout</span>
        timeout &amp;&amp; <span class="hljs-built_in">clearTimeout</span>(timeout);

        <span class="hljs-comment">// Make API Call after 1 second</span>
        timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            axios.get(<span class="hljs-string">`/suggestions?q=<span class="hljs-subst">${value}</span>`</span>)
                .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span>
                      dispatch(loadSuggestionsSuccess(response.data.suggestions)))
                .catch(<span class="hljs-function">() =&gt;</span> dispatch(loadSuggestionsFailed()))
        }, <span class="hljs-number">1000</span>, value);
    }
}
</code></pre>
<p>It requires a global variable <code>timeout</code>. When we start using global variables, our action creators are not longer pure functions. It also becomes difficult to unit test the action creators that use a global variable.</p>
<p>We can implement the same with redux-observable using the <code>.debounce</code> operator.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> loadSuggestionsEpic = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> action$.pipe(
    ofType(<span class="hljs-string">'VALUE_CHANGED'</span>),
    debounce(<span class="hljs-number">1000</span>),
    mergeMap(<span class="hljs-function"><span class="hljs-params">action</span> =&gt;</span> <span class="hljs-keyword">from</span>(axios.get(<span class="hljs-string">`/suggestions?q=<span class="hljs-subst">${action.payload.value}</span>`</span>)).pipe(
        map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> loadSuggestionsSuccess(response.data.suggestions)),
        catchError(<span class="hljs-function">() =&gt;</span> loadSuggestionsFailed())
    )),
    startWith(loadSuggestionsInProgress())
);
</code></pre>
<p>Now, our action creators can be cleaned up, and more importantly, they can be pure functions again.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">valueChanged</span>(<span class="hljs-params">value</span>) </span>{
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">type</span>: <span class="hljs-string">'VALUE_CHANGED'</span>,
        <span class="hljs-attr">payload</span>: {
            value
        }
    }
}
</code></pre>
<h3 id="heading-3-request-cancellation">3. Request Cancellation</h3>
<p><strong>Usecase:</strong> Continuing the previous use-case, assume that the user didn't type anything for 1 second, and we made our 1st API call to fetch the suggestions. </p>
<p>Let's say the API itself takes an average of 2-3 seconds to return the result. Now, if the user types something while the 1st API call is in progress, after 1 second, we will make our 2nd API. We can end up having two API calls at the same time, and it can create a race condition. </p>
<p>To avoid this, we need to cancel the 1st API call before making the 2nd API call.</p>
<p>A redux-thunk implementation will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> timeout;
<span class="hljs-keyword">var</span> cancelToken = axios.cancelToken;
<span class="hljs-keyword">let</span> apiCall;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">valueChanged</span>(<span class="hljs-params">value</span>) </span>{    
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-params">dispatch</span> =&gt;</span> {
        dispatch(loadSuggestionsInProgress());
        dispatch({
            <span class="hljs-attr">type</span>: <span class="hljs-string">'VALUE_CHANGED'</span>,
            <span class="hljs-attr">payload</span>: {
                value
            }
        });

        <span class="hljs-comment">// If changed again within 1 second, cancel the timeout</span>
        timeout &amp;&amp; <span class="hljs-built_in">clearTimeout</span>(timeout);

        <span class="hljs-comment">// Make API Call after 1 second</span>
        timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-comment">// Cancel the existing API</span>
            apiCall &amp;&amp; apiCall.cancel(<span class="hljs-string">'Operation cancelled'</span>);

            <span class="hljs-comment">// Generate a new token</span>
            apiCall = cancelToken.source();


            axios.get(<span class="hljs-string">`/suggestions?q=<span class="hljs-subst">${value}</span>`</span>, {
                <span class="hljs-attr">cancelToken</span>: apiCall.token
            })
                .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> dispatch(loadSuggestionsSuccess(response.data.suggestions)))
                .catch(<span class="hljs-function">() =&gt;</span> dispatch(loadSuggestionsFailed()))

        }, <span class="hljs-number">1000</span>, value);
    }
}
</code></pre>
<p>Now, it requires another global variable to store the Axios's cancel token. More global variables = more impure functions!</p>
<p>To implement the same using redux-observable, all we need to do is replace <code>.mergeMap</code> with <code>.switchMap</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> loadSuggestionsEpic = <span class="hljs-function">(<span class="hljs-params">action$, state$</span>) =&gt;</span> action$.pipe(
    ofType(<span class="hljs-string">'VALUE_CHANGED'</span>),
    throttle(<span class="hljs-number">1000</span>),
    switchMap(<span class="hljs-function"><span class="hljs-params">action</span> =&gt;</span> <span class="hljs-keyword">from</span>(axios.get(<span class="hljs-string">`/suggestions?q=<span class="hljs-subst">${action.payload.value}</span>`</span>)).pipe(
        map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> loadSuggestionsSuccess(response.data.suggestions)),
        catchError(<span class="hljs-function">() =&gt;</span> loadSuggestionsFailed())
    )),
    startWith(loadSuggestionsInProgress())
);
</code></pre>
<p>Since it doesn't require any changes to our action creators, they can continue to be pure functions.</p>
<p>Similarly, there are many use-cases where Redux-Observables actually shines! For example, polling an API, showing snack bars, <a target="_blank" href="https://techinscribed.com/websocket-connection-reconnection-rxjs-redux-observable/">managing WebSocket connections</a>, etc.</p>
<h2 id="heading-to-conclude">To Conclude</h2>
<p>If you are developing a Redux application that involves such complex use-cases, it is highly recommended to use Redux-Observables. After all, the benefits of using it are directly proportional to the complexity of your application, and it is evident from the above mentioned practical use-cases.</p>
<p>I strongly believe using the right set of libraries will help us to <a target="_blank" href="https://techinscribed.com/clean-react-architecture-with-redux-immer-typescript-redux-observable/">develop much cleaner and maintainable applications</a>, and in the long term, the benefits of using them will outweigh the drawbacks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An intro to Observables and how they are different from promises ]]>
                </title>
                <description>
                    <![CDATA[ By Anchal Nigam ‘Observables’, ‘Observables’, ‘Observables’...Yes! Today, we will talk about this often discussed word of the market. We'll also learn how they are different from Promises (haven't heard about Promises? Not to worry! You will know mor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-observables-how-they-are-different-from-promises/</link>
                <guid isPermaLink="false">66d45d9f680e33282da25e22</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ observables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 01 Oct 2019 20:29:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/code_feature.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Anchal Nigam</p>
<p>‘<strong>Observables</strong>’, ‘<strong>Observables</strong>’, ‘<strong>Observables</strong>’...Yes! Today, we will talk about this often discussed word of the market. We'll also learn how they are different from Promises (haven't heard about Promises? Not to worry! You will know more soon). Let’s start!</p>
<p>I first encountered the term <strong>Observable</strong> when I started learning Angular. Although it’s not an Angular-specific feature, it’s a new way of handling <strong>async</strong> requests.  Async request?  You know it, right? No! It’s ok. Let’s first understand what’s an <strong>async</strong> request is then.</p>
<h2 id="heading-async-requests">Async Requests</h2>
<p>Well! You must have read about asynchronous features in the JavaScript world. '<strong>Asynchrony</strong>' in the computer world means that the flow of the program occurs independently. It does not wait for a task to get finished. It moves to the next task. </p>
<p>Now, you might be thinking - what happens to the task that is not finished? The co-worker handles those unfinished tasks. Yes! In the background, a co-worker works and handles those unfinished tasks and once they are done, it sends data back. </p>
<p>This can bring up another question of how we handle the data that is returned. The answer is <strong>Promises</strong>, <strong>Observables</strong>, <strong>callbacks</strong> and many more. </p>
<p>We know that these asynchronous operations return responses, either some data after success or an error. To handle this, concepts like <strong>Promises</strong>, <strong>callbacks</strong>, <strong>observables</strong> came into the market. Well! I will not get into them now as we have deviated from our sub topic i.e '<strong>async</strong>' request. (Don't worry! These topics will be discussed soon).</p>
<p>After discussing the above points, you might ha have got a rough picture of what the <strong>async</strong> request is. Let’s clear it up. An <strong>Async</strong> request is one where the client does not wait for the response. Nothing is blocked. Let’s understand this concept by looking at a very common scenario.</p>
<p>In the web world, it's quite common to hit the server to get data like the details of a user, a list, and so on. We know it will take time and anything can follow (success/failure). </p>
<p> this case, instead of waiting for data to come, we handle it asynchronously (no waiting) so that our application does not get blocked. Such requests are asynchronous requests. I think now we are clear with it. So let's see how we can actually handle these async requests.</p>
<p>As I already told you, Observables gave us a new way of handling async requests. The other ways are promises, callbacks, and async/await. These are the popular ways. Let’s have a look at two of them which are callbacks and promises.</p>
<h2 id="heading-callbacks">Callbacks</h2>
<p>Callbacks are quite a common one. Callback functions (as their name suggests) are called at the back. That is when the request gets completed and returns the data or error, these functions get called. Have a look at the code for a better understanding:</p>
<pre><code><span class="hljs-keyword">const</span> request = <span class="hljs-built_in">require</span>(‘request’);
request(<span class="hljs-string">'https://www.example.com'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, response, body</span>) </span>{
  <span class="hljs-keyword">if</span>(error){
    <span class="hljs-comment">// Error handling</span>
  }
  <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Success </span>
  }
});
</code></pre><p>This is one way of handling an async request. But what happens when we want to again request to the server for data after the success of the first request? What if we want to make a third request after that successful second request? Horrible! </p>
<p>At this point, our code will become messy and less readable. This is called ‘<strong>callback</strong> <strong>hell</strong>’. To overcome it, promises came around. They offer a better way of handling an async request that improves code readability. Let’s understand a bit more.</p>
<h2 id="heading-promises">Promises</h2>
<p>Promises are objects that promise they will have value in the near future - either a success or failure. Promises have their own methods which are <strong>then</strong> and <strong>catch</strong>. <strong>.then()</strong> is called when success comes, else the <strong>catch()</strong> method calls.  <strong>Promises</strong> are created using the <strong>promise</strong> constructor. Have a look at code to better understand.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myAsyncFunction</span>(<span class="hljs-params">name</span>)</span>{
     <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
          <span class="hljs-keyword">if</span>(name == ‘Anchal’){
               resolve(‘Here is Anchal’)
         }
         <span class="hljs-keyword">else</span>{
              reject(‘Oops! This is not Anchal’)
        }

     }
} 

myAsyncFunction(‘Anchal’)
.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">val</span>)</span>{
      <span class="hljs-comment">// Logic after success</span>
      <span class="hljs-built_in">console</span>.log(val)     <span class="hljs-comment">// output -  ‘Here is Anchal’</span>
})
.catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">val</span>)</span>{
    <span class="hljs-comment">//Logic after failure</span>
     <span class="hljs-built_in">console</span>.log(val)     <span class="hljs-comment">// output - ‘Oops! This is not Anchal’</span>
})
</code></pre><p>As you can see, <strong>myAsyncFunction</strong> is actually promising that it will have some value in near future. <strong>.then()</strong> or <strong>.catch()</strong> is called according to the promise's status. </p>
<p><strong>Promises</strong> improve <strong>code</strong> <strong>readability</strong>. You can see how readable the code is by using promises. Better handling of async operations can be achieved using Promises. This is a brief introduction of what promises are, how they handle data and what beauty promises carry.</p>
<p>Now, it's time to learn about our main topic: Observables.</p>
<h2 id="heading-what-are-observables">What are Observables?</h2>
<p>Observables are also like callbacks and promises - that are responsible for handling async requests. Observables are a part of the <strong><em>RXJS</em></strong> library. This library introduced Observables. </p>
<p>Before understanding what an observable actually is, you must understand two communication models: <strong>pull</strong> and <strong>push</strong>. These two concepts are protocols of how producers of data communicate with the consumers of data.</p>
<h3 id="heading-pull-amp-push-model">Pull &amp; Push Model</h3>
<p>As I have already told you, Push and Pull are communication protocols between data producers and consumers.  Let’s understand both one by one.</p>
<p><strong>Pull Model:</strong> In this model, the <strong>consumer</strong> of data is <strong>king</strong>. This means that the consumer of data determines when it wants data from the producer. The producer does not decide when the data will get delivered. You can better understand if you relate <strong>functions</strong> to it.</p>
<p>As we know, functions are responsible for doing some task. For example, <strong>dataProducer</strong> is a function which is simply returning a string, like "<strong>Hi</strong> <strong>Observable</strong>".</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dataProducer</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-keyword">return</span> ‘Hi Observable’;
}
</code></pre><p>Now, you can see that the above function is not going to decide when it will deliver the ‘Hi Observable’ string. It will decide by the consumer, that is code that calls this function. Consumer is king. The reason why it is called a pull model is that <strong>pull</strong> task is determining the communication.  This is the <strong>pull</strong> <strong>Model</strong>. Now, let’s go into the <strong>Push</strong> <strong>Model</strong><em>.</em></p>
<p><strong>Push Model:</strong> In this model, the <strong>producer</strong> of data is <strong>king</strong>. Producer determines when to send data to consumer. The Consumer does not know when data is going to come. Let’s understand it by taking an example:</p>
<p>I hope you remember <strong>promises</strong><em>.</em> Yes, <strong>Promises</strong> follow the <strong>push</strong> <strong>model</strong><em>.</em>  A Promise (producer) delivers data to the callback (<em>.then()</em> - consumer). Callbacks do not know when data is going to come. Here, <strong>promise</strong> (producer) is king. It is determining the communication. That’s why it's called <strong>Push</strong> <strong>Model</strong> as the producer is in charge.</p>
<p>Like promises, Observables also follow the push model. How? You will get the answer once I elaborate on observables. Let’s get back to observables then.</p>
<h2 id="heading-observables-as-functions">Observables as functions</h2>
<p>To simply understand, you can think of observables as functions. Let’s have a look at the below examples:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dataProducer</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> ‘Hi Observable’
}

<span class="hljs-keyword">var</span> result = dataProducer();
<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// output -  ‘Hi Observable’</span>
</code></pre><p>You can get the same behaviour using an observable: </p>
<pre><code><span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{

   observer.next(‘Hi Observable’);

})

observable.subscribe(<span class="hljs-function">(<span class="hljs-params">data</span>)=&gt;</span>{
   <span class="hljs-built_in">console</span>.log(data);    <span class="hljs-comment">// output - ‘Hi Observable’</span>
})
</code></pre><p>From above, you can see both functions and observables show the same behaviour. This may bring a question to your mind - are observables the same as functions? No. I'll clarify in a minute why the answer is no. Have a look at an elaborate version of the above example.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dataProducer</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> ‘Hi Observable’;
    <span class="hljs-keyword">return</span> ‘Am I understandable?’ <span class="hljs-comment">// not a executable code.</span>
}

<span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{

   observer.next(‘Hi Observable’);
   observer.next( ‘Am I understandable?’ );

})

observable.subscribe(<span class="hljs-function">(<span class="hljs-params">data</span>)=&gt;</span>{
   <span class="hljs-built_in">console</span>.log(data);    
})

<span class="hljs-attr">Output</span> :
‘Hi Observable’
‘Am I understandable?’
</code></pre><p>I hope you can now see what difference I wanted to address. From above, you can see, <strong>both functions and observables are lazy</strong>. We need to call (functions) or subscribe (observables) to get the results. </p>
<p><strong>Subscriptions to observables are quite similar to calling a function.</strong> But where observables are different is in their ability to return <strong>multiple</strong> <strong>values</strong> called <strong>streams</strong> (a stream is a sequence of data over time). </p>
<p>Observables not only able to return a value <strong>synchronously</strong>, but also <strong>asynchronously</strong>.</p>
<pre><code><span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{
   observer.next(‘Hi Observable’);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
        observer.next(‘Yes, somehow understandable!’)
    }, <span class="hljs-number">1000</span>)   

   observer.next( ‘Am I understandable?’ );
})

<span class="hljs-attr">output</span> :

‘Hi Observable’
‘Am I understandable?’ 
Yes, somehow understandable!’.
</code></pre><p>In short, you can say <strong>observables are simply a function that are able to give multiple values over time, either synchronously or asynchronously</strong><em><strong>.</strong></em></p>
<p>You now have an outline about observables. But let’s understand them more by looking into different phases of observables.</p>
<h2 id="heading-observable-phases">Observable Phases</h2>
<p>We have already seen from the above example how observables create and execute and come into play by subscription. Hence, there are four stages through which observables pass. They are:</p>
<ol>
<li><strong>Creation</strong></li>
<li><strong>Subscription.</strong></li>
<li><strong>Execution</strong></li>
<li><strong>Destruction.</strong></li>
</ol>
<p><strong>Creation of an observable</strong> is done using a <strong>create</strong> <strong>function</strong>.</p>
<pre><code><span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{
})
</code></pre><p>To make an <strong>observable</strong> <strong>work</strong>, we have to <strong>subscribe</strong> it. This can be done using the subscribe method.</p>
<pre><code>observable.subscribe(<span class="hljs-function">(<span class="hljs-params">data</span>)=&gt;</span>{
   <span class="hljs-built_in">console</span>.log(data);    
})
</code></pre><p>Execution of observables is what is inside of the create block. Let me illustrate with the help of an example:</p>
<pre><code><span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{

   observer.next(‘Hi Observable’);        
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
        observer.next(‘Yes, somehow understandable!’)
    }, <span class="hljs-number">1000</span>)   

   observer.next( ‘Am I understandable?’ );

})
</code></pre><p>The above code inside the create function is observable execution. The <strong>three</strong> types of <strong>values</strong> that an observable can deliver to the subscriber are:</p>
<pre><code>observer.next(‘hii’);<span class="hljs-comment">//this can be multiple (more than one)</span>

observer.error(‘error occurs’) <span class="hljs-comment">// this call whenever any error occus.</span>

Observer.complete(‘completion <span class="hljs-keyword">of</span> delivery <span class="hljs-keyword">of</span> all values’) <span class="hljs-comment">// this tells the subscriptions to observable is completed. No delivery is going to take place after this statement.</span>
</code></pre><p>Let’s have a look below to understand all three values:</p>
<pre><code><span class="hljs-keyword">var</span> observable = Rx.Observable.create(<span class="hljs-function">(<span class="hljs-params">observer: any</span>) =&gt;</span>{
<span class="hljs-keyword">try</span> {
   observer.next(‘Hi Observable’);                                       
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
        observer.next(‘Yes, somehow understandable!’)
    }, <span class="hljs-number">1000</span>)   

   observer.next( ‘Am I understandable?’ );

   observer.complete();

   observer.next(‘lAST DELIVERY?’ );  
   <span class="hljs-comment">// above block is not going to execute as completion notification is      already sent.</span>
   }
<span class="hljs-keyword">catch</span>(err){
     observer.error(err);    
  }

})
</code></pre><p>Last phase that comes into the market is destruction. After an error or a complete notification, the observable is automatically unsubscribed. But there are cases where we have to manually <strong>unsubscribe</strong> it. To manually do this task, just use:</p>
<pre><code><span class="hljs-keyword">var</span> subscription = observable.subscribe(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(x)); <span class="hljs-comment">// Later: subscription.unsubscribe();</span>
</code></pre><p>This is all about the different phases through which an observable passes.</p>
<p>I think, now, we know what observables are? But what about the other question which is - how observables are different from promises? Let’s find the answer to it.</p>
<h2 id="heading-promises-vs-observables">Promises vs observables</h2>
<p>As we know, promises are for handling async requests and observables can also do the same. But where do they differ?</p>
<h3 id="heading-observables-are-lazy-whereas-promises-are-not">Observables are lazy whereas promises are not</h3>
<p>This is pretty self-explanatory: observables are lazy, that is we have to subscribe observables to get the results. In the case of promises, they execute immediately.</p>
<h3 id="heading-observables-handle-multiple-values-unlike-promises">Observables handle multiple values unlike promises</h3>
<p>Promises can only provide a single value whereas observables can give you multiple values.</p>
<h3 id="heading-observables-are-cancelable">Observables are cancelable</h3>
<p>You can cancel observables by unsubscribing it using the <strong>unsubscribe</strong> method whereas promises don’t have such a feature.</p>
<h3 id="heading-observables-provide-many-operators">Observables provide many operators</h3>
<p>There are many operators like <strong>map</strong><em>,</em> <strong>forEach</strong><em>,</em> <strong>filter</strong> etc. Observables provide these whereas promises does not have any operators in their bucket.</p>
<p>These are features that makes observables different from promises.</p>
<p>Now, it's time to end. I hope you have a better understanding of the hot topic of observables!</p>
<p>Thanks for reading!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSP vs RxJS: what you don’t know. ]]>
                </title>
                <description>
                    <![CDATA[ By Kevin Ghadyani What happened to CSP? _Photo by [Unsplash](https://unsplash.com/@lamppidotco?utm_source=medium&utm_medium=referral" rel="noopener" target="_blank" title="">James Pond on <a href="https://unsplash.com?utm_source=medium&utm_medium=re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/csp-vs-rxjs-what-you-dont-know-1542cd5dd100/</link>
                <guid isPermaLink="false">66c348353a31d2480bb383a0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 04 Apr 2019 17:18:15 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*ColTdidsgUyGVesk" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Kevin Ghadyani</p>
<h4 id="heading-what-happened-to-csp">What happened to CSP?</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*ColTdidsgUyGVesk" alt="Image" width="800" height="533" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@lamppidotco?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="_blank" title=""&gt;James Pond on &lt;a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="<em>blank" title=")</em></p>
<p>You probably clicked this article thinking “what is CSP?” It’s <strong>communicating sequential processes</strong>. Still baffled?</p>
<p>CSP is a method of communicating between different functions (generators) in your code using a shared channel.</p>
<p>What in the world does that mean? Lemme tell it to ya straight. There’s this concept of a channel. Think of it like a queue. You can put stuff on it and take stuff off it.</p>
<p>So with two functions, you can have one adding stuff on the channel (producer) and another pulling things off and doing some work (consumer).</p>
<p>A typical advanced use case would be multiple producers and one consumer. That way you can control the data you’re getting, but you can have multiple things giving it to you.</p>
<p>Unlike RxJS, these channels are automatic. You don’t get values willy-nilly, you have to ask for them.</p>
<h3 id="heading-using-csp">Using CSP</h3>
<p>Here’s a small CSP example using the super simple (and dead) library <a target="_blank" href="https://www.npmjs.com/package/channel4">Channel4</a>:</p>
<p>CSP channels run asynchronously. So as soon as this runs, the synchronous “DONE” message gets logged first. Then our channel takers are executed in order.</p>
<p>The most-interesting thing to me is the blocking (but async) nature of CSP. Notice how we created the third <code>take</code> before putting “C” on the channel. Unlike the first two <code>take</code> functions, the third one doesn’t have anything to take. Once something comes into the channel, it immediately takes it.</p>
<p>Also note, consumers need to be constantly taking things off the channel until that channel closes. That’s why “D” is never logged. You need to define another <code>take</code> to grab the next value off the channel.</p>
<p>With observables, you’re given values so you don’t have to worry about manually pulling them off. If you want to buffer those values, RxJS provides quite a few pipeline methods for that very purpose. No need to use CSP.</p>
<p>The entire concept behind observables is that every listeners gets the same data as soon as the observer calls <code>next</code>. With CSP, it’s like the IxJS approach where you’re dealing with data in chunks.</p>
<h3 id="heading-csp-is-dead">CSP IS DEAD!?</h3>
<p>You can find CSP implementations in <a target="_blank" href="https://godoc.org/github.com/thomas11/csp">Go</a> and <a target="_blank" href="https://github.com/clojure/core.async">Closure</a>. In JavaScript, all but a couple CSP libraries are dead and even then, their audience is small ?.</p>
<p>I found out about CSP from <a target="_blank" href="https://www.youtube.com/watch?v=r7yWWxdP_nc">Vincenzo Chianese’s awesome talk</a>. He recommended this high-end library called <a target="_blank" href="https://github.com/ubolonton/js-csp">js-csp</a>. Sadly, it’s no longer maintained.</p>
<p>Based on what he said in his 2017 talk, it seemed like a big deal. He talked about how transducers were going to to explode in a few months and how js-csp already had support for them.</p>
<p>It looked like CSP could fundamentally change how you developed async applications in JavaScript. But none of that ever happened. Transducers died away; replaced by libraries like RxJS, and the hype around CSP dissolved.</p>
<p>Vincenzo did note how CSP is a whole ‘nother level above promises. He’s right. The power you get having multiple functions interacting asynchronously is incredible.</p>
<p>Promises, by their eager nature, aren’t even in the same ballpark. Little did he know the last few CSP libraries would end up supporting promises under-the-hood ?.</p>
<h3 id="heading-csp-alternative-redux-saga">CSP Alternative: Redux-Saga</h3>
<p>If you’ve ever used Redux-Saga, the ideas and concepts around CSP probably sound familiar. That’s because they are. In fact, Redux-Saga is an implementation of CSP in JavaScript; the most popular by far.</p>
<p>There’s even a concept of “channels” in Redux-Sagas:<br><a target="_blank" href="https://github.com/redux-saga/redux-saga/blob/master/docs/advanced/Channels.md">https://github.com/redux-saga/redux-saga/blob/master/docs/advanced/Channels.md</a></p>
<p>Channels receive information from external events, buffer actions to the Redux store, and communicate between two sagas. It’s the same way they’re used in CSP with the same <code>take</code> and <code>put</code> functions.</p>
<p>Pretty cool to see an actual implementation of CSP in JavaScript, but strange very few have noticed it. That shows you how little CSP took off before dying.</p>
<h3 id="heading-csp-alternative-redux-observable">CSP Alternative: Redux-Observable</h3>
<p>You might’ve heard of something called Redux-Observable. This is a similar concept to CSP and Redux-Saga, but instead of the imperative style of generators, it takes a functional approach and utilizes RxJS pipelines referred to as “epics”.</p>
<p>In Redux-Observable, everything happens through two subjects: <code>action$</code> and <code>state$</code>. Those are your channels.</p>
<p>Instead of manually taking and putting, you’re listening for specific actions as a consumer of an action or state channel. Each epic has the ability of also being a producer by sending actions through the pipeline.</p>
<p>If you want to build a queue in Redux-Observable just like CSP, it’s a little more complicated as there’s no operator available for this purpose, but it’s entirely possible.</p>
<p>I created a repl that does just that:</p>
<p>Compared to our earlier CSP example, this is what you can expect to see:</p>
<p>The example only requires RxJS and everything is in a single file for simplicity. As you can see, it’s a lot harder to queue up items in RxJS the same way you might with CSP. It’s entirely possible, but requires a lot more code.</p>
<p>Personally, I’d love to see RxJS add an operator like <code>bufferWhen</code> that allows you to divvy out individual items instead of the entire buffer. Then you could accomplish the CSP-style in Redux-Observable a lot easier.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>CSP was a cool concept, but it’s dead in JavaScript. Redux-Saga and Redux-Observable are worthy alternatives.</p>
<p>Even with the ability to integrate with transducer libraries, RxJS still has a clear leg-up. It’s massive community of educators and production applications makes it hard to compete.</p>
<p>That’s why I think CSP died in JavaScript.</p>
<h3 id="heading-more-reads">More Reads</h3>
<p>If you liked what you read, please checkout my other articles on similar eye-opening topics:</p>
<ul>
<li><a target="_blank" href="https://medium.com/@Sawtaytoes/redux-observable-can-solve-your-state-problems-15b23a9649d7">Redux-Observable Can Solve Your State Problems</a></li>
<li><a target="_blank" href="https://itnext.io/redux-observable-without-redux-ff4a2b5a4b39">Redux-Observable without Redux</a></li>
<li><a target="_blank" href="https://itnext.io/the-definitive-guide-to-callbacks-in-javascript-44a39c065292">Callbacks: The Definitive Guide</a></li>
<li><a target="_blank" href="https://itnext.io/promises-the-definitive-guide-6a49e0dbf3b7">Promises: The Definitive Guide</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Subjects in Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Dler Ari A Subject is a “special” type of observable that allows us to broadcast values to multiple subscribers. The cool thing about Subjects, is that it provides a real-time response. For instance, if we have a subject with 10 subscribers, whene... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-subjects-in-reactive-programming-bbdc8fed7b6/</link>
                <guid isPermaLink="false">66d45e47d14641365a0508b8</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ observables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 28 Mar 2019 16:15:19 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*6gi30QcIoPkwcxpz5d4wkg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dler Ari</p>
<p>A Subject is a “special” type of observable that allows us to broadcast values to multiple subscribers. The cool thing about Subjects, is that it provides a real-time response.</p>
<p>For instance, if we have a subject with 10 subscribers, whenever we push values to the subject, we can see the value captured by each subscriber</p>
<p>This introduces a couple challenges; what if we push some values, and then subscribe, or vice-verse? Timing plays an important role, if we subscribe late, we won’t be able to access the values, similar to if someone enters a live-sport event on TV 30 minutes later.</p>
<p>Luckily, we have 4 types of Subjects that allows us to “time travel” in which we can access values even though we subscribe late or not.</p>
<h4 id="heading-topics-well-cover">Topics we’ll cover:</h4>
<ol>
<li>What is a Subject with a practical example</li>
<li>BehaviorSubject: Get the last message</li>
<li>ReplaySubject: Time travel</li>
<li>AsyncSubject: Once completed, get the last message</li>
</ol>
<h3 id="heading-1-what-is-a-subject">1. What is a Subject?</h3>
<p>As mentioned, a Subject is nothing more like an observable with a few more characteristics. An observable is by definition an <a target="_blank" href="https://rxjs.dev/guide/overview">invokable collection</a> that emits data once subscribed. Meanwhile, a Subject is where we control the state of “when to emit data” to multiple subscribers.</p>
<p>A Subject allows us to invoke methods like <code>.next()</code>, <code>.complete()</code> and <code>.error()</code> outside, while in an observable, we invoke these methods as callbacks.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Creating an Observable</span>
<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function">(<span class="hljs-params">observer</span>) =&gt;</span> {
    observer.next(<span class="hljs-number">10</span>);
    observer.next(<span class="hljs-number">5</span>);
    observer.complete();
});

<span class="hljs-comment">// Creating a Subject</span>
<span class="hljs-keyword">const</span> subject = <span class="hljs-keyword">new</span> Subject();
subject.next(<span class="hljs-number">10</span>);
subject.next(<span class="hljs-number">5</span>);
subject.complete();
</code></pre>
<h4 id="heading-practical-example-lets-build-a-simple-chat-group-using-a-subject">Practical example: Let’s build a simple chat group using a Subject</h4>
<p>Let’s imagine we are building a simple chat app where people can post messages to the chat group. The first step is to create an instance of the Subject, and then assign it to a <code>chatGroup</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create subject "Observable"</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> Subject();
</code></pre>
<p>Now that our chat group (Subject) is created, the next thing to do is add messages. Let’s create a typical conversation between two friends.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Push values to the stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);
</code></pre>
<p>So far so good — now we have 4 messages posted in our chat group, so what happens if we subscribe? Or let’s say a new friend named John wants to join the conversation. Is he be able to see the old messages?</p>
<pre><code class="lang-js"><span class="hljs-comment">// Print messages</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})
</code></pre>
<p>Unfortunately not, John misses the conversation because he’s subscribes late. This is a perfect example of how reactive programming works — the idea of values passing over time, and thus, we must subscribe in the right time to access the values.</p>
<p>To further elaborate on the previous example, what if John enters in the middle of the conversation?</p>
<pre><code class="lang-js"><span class="hljs-comment">// Push values to the stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);

<span class="hljs-comment">// John enters the conversation </span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
});

chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// David - Interesting, which one is the hottest?</span>
<span class="hljs-comment">// Peter - Game of Thrones!</span>
</code></pre>
<p>Once John subscribes, he sees the two last messages. The Subject is doing what it’s intended to do. But what if we want John to view all messages, or just the last one, or get notified when a new message is posted?</p>
<p>In general, these Subjects are mostly similar, but each one provides some extra functionality, let’s describe them one by one.</p>
<h3 id="heading-2-behaviorsubject-get-last-message">2. BehaviorSubject: Get last message</h3>
<p>The BehaviorSubject is similar to a Subject except it requires an initial value as an argument to mark the starting point of the data stream. The reason is because when we subscribe, it returns the last message. This is similar concept when dealing with arrays; where we do <code>array.length-1</code> to get the latest value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {BehaviorSubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> BehaviorSubject(<span class="hljs-string">'Starting point'</span>);

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// Peter - Game of Thrones!</span>
</code></pre>
<h3 id="heading-3-replaysubject-time-travel">3. ReplaySubject: Time travel</h3>
<p>The ReplaySubject, as the name implies, once subscribed it broadcasts all messages, despite if we subscribed late or not. It’s like time travel, where we can access all the values that were broadcast.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">import</span> { ReplaySubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> ReplaySubject();

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// David - Hi, which hot series do you recommend?'</span>
<span class="hljs-comment">// Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>
<span class="hljs-comment">// David - Interesting, which one is the hottest?'</span>
<span class="hljs-comment">// Peter - Game of Thrones!'</span>
</code></pre>
<h3 id="heading-4-asyncsubject-once-completed-get-last-message">4. AsyncSubject: Once completed, get last message</h3>
<p>The AsyncSubject is similar to BehaviorSubject in terms of emitting the last value once subscribed. The only difference is that it requires a <code>complete()</code> method to mark the stream as completed. Once that is done, the last value is emitted.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { AsyncSubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> AsyncSubject();

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

chatGroup.complete(); <span class="hljs-comment">// &lt;-- Mark the stream as completed</span>

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// Peter - Game of Thrones!'</span>
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>Back to our previous example with John, we can now decide if we want John to access the whole conversation (ReplaySubject), the last message (BehaviorSubject), or the last message once the conversation completes (AsyncSubject).</p>
<p>If you ever struggle to identify if a Subject is the right way to go, the article “<a target="_blank" href="http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx">To Use a Subject or Not to Use a Subject</a>” by Dave Sixton describes when to use Subjects based on two criteria:</p>
<ol>
<li>Only when one want to <strong>convert</strong> a cold Observable into a hot observable.</li>
<li><strong>Generate</strong> a hot observable that passes data continuously.</li>
</ol>
<p>In short, only creativity limits the potential use of reactive programming. There will be some scenarios where Observables do most of the heavy-lifting, but understanding what Subjects are, and what type of Subjects exists, will definitely improve your reactive programming skills.</p>
<p>If you are interested to learn more about the web-ecosystem, here are few articles I’ve written, enjoy.</p>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-comparison-between-angular-and-react-and-their-core-languages-9de52f485a76">A comparison between Angular and React</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773">A practical guide to ES6 modules</a></li>
<li>[How to perform HTTP requests using the Fetch API](http://A practical ES6 guide on how to perform HTTP requests using the Fetch API)</li>
<li><a target="_blank" href="https://medium.freecodecamp.org/learn-these-core-javascript-concepts-in-just-a-few-minutes-f7a16f42c1b0?gi=6274e9c4d599">Important web concepts to learn</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/7-javascript-methods-that-will-boost-your-skills-in-less-than-8-minutes-4cc4c3dca03f">Boost your skills with these JavaScript methods</a></li>
<li><a target="_blank" href="https://codeburst.io/learn-how-to-create-custom-bash-commands-in-less-than-4-minutes-6d4ceadd9590">Create custom bash commands</a></li>
</ul>
<p>You can find me on Medium where I publish on a weekly basis. Or you can follow me on <a target="_blank" href="http://twitter.com/dleroari">Twitter</a>, where I post relevant web development tips and tricks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to observables in Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Dler Ari One of the most challenging things for new developers to learn is the observer pattern. Understanding how to effectively use it with RxJS to deal with asynchronous data such as user events, HTTP requests or any other events that require w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-observables-in-reactive-programming-1cfd3e23bb94/</link>
                <guid isPermaLink="false">66d45e45182810487e0ce157</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 22 Mar 2019 16:40:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*5FEY_E1x_bCfWpz3RiIFXw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dler Ari</p>
<p>One of the most challenging things for new developers to learn is the observer pattern. Understanding how to effectively use it with RxJS to deal with asynchronous data such as user events, HTTP requests or any other events that require waiting for something to complete is tricky.</p>
<p>What most people struggle with is the new approach. It requires a different mindset where visualization plays an important role. We think of data as a sequence of values that passes over time rather than as one single value that is retrieved once. This mindset is known as reactive programming.</p>
<p>Since the Observer pattern is a fairly large ecosystem consisting of many important parts, I’ve chosen to narrow it down by focusing on Observables only. I’ll share other articles soon that cover the rest of the Observer pattern, such as how to deal with RxJS.</p>
<h4 id="heading-topics-well-cover">Topics we’ll cover:</h4>
<ol>
<li>What does asynchronous really mean?</li>
<li>Which pattern to use (Observer or Promise)</li>
<li>How to create an Observable (code examples start here)</li>
<li>How to subscribe to an Observable</li>
<li>How to unsubscribe to an Observable</li>
</ol>
<h3 id="heading-1-what-does-asynchronous-really-mean">1. What does asynchronous really mean?</h3>
<p>One of the things with the web, and the majority of languages, is that once you ask for data such as requesting a list of users from the server, you can’t guarantee that the data will be returned. There is an uncertainty issue.</p>
<p>One of the reasons may be that the data is not present, the server may be broken, or the HTTP URL is not valid because someone has changed the query string.</p>
<p>For that reason, along with a few others, we need to deal with such data asynchronously. We request the list of users, and wait until it is retrieved, but don’t stop the whole application for a simple operation.</p>
<p>It’s like telling a coworker to solve a task instead of sending the whole team; that would be an expensive and not a wise approach to take.</p>
<p>Let’s clarify a misconception: the terms synchronous or asynchronous have nothing to do with multi-threading, where operations are executed at the same time. It simply means the operations are either <strong>dependent on</strong> or <strong>independent from</strong> each other, that’s it.</p>
<p>Let’s compare the difference between synchronous and asynchronous to better understand how they really work.</p>
<h4 id="heading-what-is-synchronous">What is Synchronous?</h4>
<p>With Synchronous events, you wait for one to finish before moving on to another task.</p>
<p><strong>Example:</strong> You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you. Answered by <a target="_blank" href="https://stackoverflow.com/users/1428344/themightysapien">themightysapien</a>.</p>
<h4 id="heading-what-is-asynchronous">What is Asynchronous?</h4>
<p>With asynchronous events, you don’t wait, you can move on to the next task until the data is available.</p>
<p><strong>Example:</strong> You are in a restaurant with many other people. You order your food. Other people can also order their food, they don’t have to wait for your food to be cooked and served to you before they can order. In the kitchen, restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked. Answered by <a target="_blank" href="https://stackoverflow.com/users/1428344/themightysapien">themightysapien</a>.</p>
<p>Alright, so in short, this allows us to either wait for operations to happen before we can move on, or not wait until the data is ready.</p>
<h3 id="heading-2-which-pattern-to-use-observer-or-promise">2. Which pattern to use (Observer or Promise)</h3>
<p>First of all, both the observer pattern and the promise pattern deal with asynchronous operations. Operations such as user events or HTTP requests, or any other events that execute independently.</p>
<p>The majority of operations today need some type of asynchronous/synchronous handling, and understanding how it works plays an important role when building robust apps.</p>
<p>It’s not meant to make your life harder, but easier. However, it thus requires a learning-curve which may be a painful approach, but the reward at the end is well worth it.</p>
<h4 id="heading-stay-with-one-pattern">Stay with one pattern</h4>
<p>The difference lies in the complexity of the application. If you deal with a small app where the task is to simply get a list of users from the server, or to show active members, then promises with the <code>Fetch API</code> (<a target="_blank" href="https://medium.freecodecamp.org/a-practical-es6-guide-on-how-to-perform-http-requests-using-the-fetch-api-594c3d91a547">read more</a>) work fine.</p>
<p>But if you deal with a large application with many asynchronous operations that require changing the data, performing multiple operations on a data stream, or reusing it in multiple places, then the observer pattern works great.</p>
<h4 id="heading-can-i-use-both-patterns-in-one-project">Can I use both patterns in one project?</h4>
<p>Yes, but it’s not recommended that you mix between two architectures which basically do the same thing (handle asynchronous events). Instead, stick with one, and learn more about it.</p>
<h4 id="heading-boost-your-skills-with-rxjs">Boost your skills with RxJS</h4>
<p>With RxJS, you have access to 189 operators with documentation + <a target="_blank" href="https://reactive.how/">other great resources</a>. And each of these operators are simply callbacks that do something on the data stream.</p>
<p>If you are familiar with JavaScript’s functional prototypes (methods) such as <code>map()</code>, <code>filter()</code>, and <code>reduce()</code>, you’ll find them in RxJS. Note, the concept is the same but the written code is not.</p>
<p>So what is the difference between these two patterns?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*EAzaxT7ejRGLcvL4pgVqPA.png" alt="Image" width="554" height="316" loading="lazy">
<em>Observable vs Promise</em></p>
<p>Here’s a quick comparison between the observer pattern and the promise pattern. The key points are that a promise emits a single value(s) once the <code>.then()</code> callback is used, while an Observable emits multiple values as a sequence of data that passes over time. Another important point is that an Observable can be canceled or retried while a promise cannot. However, there are external packages that make it possible to cancel a promise.</p>
<h3 id="heading-3-how-do-we-create-an-observable">3. How do we create an Observable?</h3>
<p>Here are a couple of ways one can create an Observable:</p>
<ul>
<li>create an Observable from scratch</li>
<li>turn a promise into an Observable</li>
<li>or use a framework that does it for you behind the scenes, such as Angular.</li>
</ul>
<blockquote>
<p>Did you know that Angular uses the Observer pattern extensively? All asynchronous operations such as HTTP GET or listening for events or value changes follow the observer pattern.</p>
</blockquote>
<p>If you ever want to mimic (test) a real-world scenario, so to say pass values over time, I highly recommend using the interval function. This passes values after x time in milliseconds. So if you have an interval where x is 2000ms — it passes each value (increments) after 2 seconds.</p>
<h3 id="heading-4-how-do-we-subscribe-to-an-observable">4. How do we subscribe to an Observable?</h3>
<p>An Observable is simply a collection of data that waits to be invoked (subscribed) before it can emit any data. If you’ve worked with promises, then the way to access the data is to chain it with the <code>then()</code> operator or use the ES6 <code>async/await</code>.</p>
<p>So to follow the previous example, how does one access the data?</p>
<p>As shown above, when we subscribe, we tell the Observable to pass us whatever it holds. It can be an array, a collection of events, or a sequence of objects and so forth.</p>
<p>A common beginner-mistake I’ve seen among developers is that they do many operations on the Observable but get frustrated because they can’t see any results. You are not alone! I’ve made this mistake a couple of times and as a thumb-rule — always remember to subscribe.</p>
<h3 id="heading-5-how-do-we-unsubscribe-to-an-observable">5. How do we unsubscribe to an Observable?</h3>
<p>It is important to unsubscribe, otherwise we end up with a memory leak which slows down the browser. If you’ve worked with Angular, there is a pipe named <code>asyncPipe</code> which subscribes and unsubscribes automatically for you.</p>
<p>The way we unsubscribe is that we create a reference to each Observable that is subscribed by creating a variable to preserve its current state. And then, for each variable, we chain it with the <code>unsubscribe()</code> method. Remember that you can only unsubscribe after you’ve subscribed. It’s fairly simple but often forgotten.</p>
<p>Notice, if you unsubscribe here, <code>Observable_1</code> and <code>Observable_2</code> will output the data before it is unsubscribe because these are cold Observables (not time-dependent), while <code>Observable_3</code> and <code>Observable_4</code> will not output anything because these are hot Observables (time-dependent).</p>
<h3 id="heading-summary">Summary</h3>
<p>As mentioned above, the most challenging part of learning the observer pattern is the mindset. A mindset where we look at values differently, such as a sequence of data that emits over time. In this article, we’ve covered types of ways we can create an Observable, as well as how to subscribe and unsubscribe.</p>
<p>I recommend using the observer pattern because it provides everything that the promise pattern offers, and much more. It also provides a few great operators to prevent users from sending thousands of unnecessary requests to the backend.</p>
<p>One of them is <code>debonceTime</code> which gives the user enough time to write a complete word, and then send one request instead of a request for every character. You can, of course, achieve this with a simple promise, but that requires some lines of code.</p>
<p>I’ll cover more about reactive programming in the near future, stay tuned!</p>
<p>If you are interested to learn more about the web-ecosystem, here are few articles I’ve written to boost your web skills, enjoy :)</p>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/7-javascript-methods-that-will-boost-your-skills-in-less-than-8-minutes-4cc4c3dca03f">Boost your skills with these JavaScript methods</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-comparison-between-angular-and-react-and-their-core-languages-9de52f485a76">A comparison between Angular and React</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773">A practical guide to ES6 modules</a></li>
<li>[How to perform HTTP requests using the Fetch API](http://A practical ES6 guide on how to perform HTTP requests using the Fetch API)</li>
<li><a target="_blank" href="https://medium.freecodecamp.org/learn-these-core-javascript-concepts-in-just-a-few-minutes-f7a16f42c1b0?gi=6274e9c4d599">Important web concepts to learn</a></li>
</ul>
<blockquote>
<p><em>If you want to become a better web developer, start your own business, teach others, or improve your development skills, you can find me on Medium where I publish on a weekly basis. Or you can follow me on <a target="_blank" href="http://twitter.com/dleroari">Twitter</a>, where I post relevant web development tips and tricks.</em></p>
<p><em>P.S. If you enjoyed this article and want more like these, please clap ❤ and share with friends that may need it, it’s good karma.</em></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ ⚡ How to never repeat the same RxJs mistakes again⚡ ]]>
                </title>
                <description>
                    <![CDATA[ By Tomas Trajan Remember: .pipe() is not .subscribe()! _Look! A lightning tip! (Original ? by M[ax Bender)](https://unsplash.com/photos/iF5odYWB_nQ?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="blank" tit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/blitz-tips-rxjs-pipe-is-not-a-subscribe-125c89437a2c/</link>
                <guid isPermaLink="false">66c3461b622ca5970af832ff</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 22 Jan 2019 13:14:28 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*8WNtSRqKD9vfik5zLqDRzw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Tomas Trajan</p>
<h4 id="heading-remember-pipe-is-not-subscribe">Remember: .pipe() is not .subscribe()!</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/fNpm-kNhaYwgz2TVveT9Zs1BYKjC9I5G6wR0" alt="Image" width="800" height="410" loading="lazy">
_Look! A lightning tip! (Original ? by M[ax Bender)](https://unsplash.com/photos/iF5odYWB_nQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<blockquote>
<p>This article is directed at the beginners trying to increase their RxJs knowledge but can also be a quick refresh or a reference to show to beginners for more experienced developers!</p>
</blockquote>
<p>Today we are going to keep it short and straight to the point!</p>
<p>Currently I am working in a rather large organization quite a few teams and projects (more than 40 SPAs) that are in the process of migration to Angular and therefore also RxJs.</p>
<p>This represents a great opportunity to get in touch with the confusing parts of RxJs which can be easy to forget once one masters the APIs and focuses on the implementation of the features instead.</p>
<h3 id="heading-the-subscribe-function">The “.subscribe()” function</h3>
<p>RxJs observable represent a “recipe” of what we want to happen. It’s declarative which means that all the operations and transformations are specified in their entirety from the get go.</p>
<p>An example of an observable stream could look something like this…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RilFbbGg9L-sldm9tExd5KJeYZDpaI-tkDB6" alt="Image" width="800" height="214" loading="lazy">
<em>Example of the RxJs observable stream declaration</em></p>
<p>This RxJs observable stream will do literally nothing by itself. To execute it we have to subscribe to it somewhere in our codebase!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/slCuDufj5NNymYAfjvD5ZjCk1ImU5j56Ydww" alt="Image" width="800" height="152" loading="lazy">
<em>This subscription will log our greetings every odd minute</em></p>
<p>In the example above, we provided a handler only for the values emitted by the observable. The subscribe function itself accepts up to three different argument to the handle <strong>next</strong> value, <strong>error</strong> or <strong>complete</strong> event.</p>
<p>Besides that we could also pass in an object with the properties listed above. Such an object is an implementation of the <code>Observer</code> interface. The advantage of observer is that we don’t have to provide implementation or at least a <code>null</code> placeholder for the handlers we are not interested in.</p>
<p>Consider the following example…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/o0QFSmaoJWlc3EB1EwioXq8y4feIBLr1JcS6" alt="Image" width="800" height="156" loading="lazy"></p>
<p>In the code above, we are passing an object literal which contains only complete handler, the normal values will be ignored and errors will bubble up the stack.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/tdaiNzIWmElXpTcw-dBTX5XNtSEspNyyAu2S" alt="Image" width="800" height="208" loading="lazy"></p>
<p>And in this example, we are passing the handler of the next error and complete it as direct arguments of the subscribe function. All unimplemented handlers have to be passed as a null or undefined until we get to the argument we’re interested in.</p>
<p>As we can see, the inline argument style of implementation of a <code>.subscribe()</code> function call is positional.</p>
<blockquote>
<p>In my experience, the inline arguments style is the one which is most common in various projects and organizations.</p>
</blockquote>
<p>Unfortunately, many times we may encounter implementation like the following…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/HzGX7f-wmb1vGY1r8A2aaKkUYhf5H74LbC9N" alt="Image" width="800" height="225" loading="lazy">
<em>Example of redundant handlers often encountered in the “wild”</em></p>
<p>The example above contains redundant handlers for both <code>next</code> and <code>error</code> handlers which <strong>do exactly nothing</strong> and could have been replaced by <code>null</code>.</p>
<blockquote>
<p>Even better would be to pass the observer object with the <code>complete</code> handler implementation, omitting other handlers altogether!</p>
</blockquote>
<h3 id="heading-the-pipe-and-the-operators">The “.pipe()” and the operators</h3>
<p>As beginners are used to providing three arguments to subscribe, they often try to implement a similar pattern when using similar operators in the pipe chain.</p>
<p>RxJs operators, which are often confused with the <code>.subscribe()</code> handlers, are <code>catchError</code> and <code>finalize</code>. They both serve a similar purpose too — the only difference being that they are used in the context of the pipe instead of the subscription.</p>
<p>In case we would like to react to the complete event of every subscription of the RxJs observable stream, we could implement <code>finalize</code> operator as a part of the observable stream itself.</p>
<blockquote>
<p>That way we don’t have to depend on the developers to implement complete handlers in the every single .subscribe() call. Remember, the observable stream can be subscribed to more than once!</p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/KyNcUrKEuK-5ho4qMmrJH9rRsgUIYBFDx8kr" alt="Image" width="800" height="228" loading="lazy">
<em>Use the finalize operator to react to the complete event of the stream independently from the subscription. (Similar to tap)</em></p>
<p>This brings us to the final and arguably most problematic pattern we may encounter when exploring various code bases: redundant operators added when trying to follow .subscribe() pattern in the .pipe() context.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VoSsjJj6f-9Tmlkpqn53d5LikSlKgaQVPMzg" alt="Image" width="800" height="243" loading="lazy"></p>
<p>Also, we might encounter its even more verbose cousin…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/XZb1uYVdeTzKVx1YSpK5NY88CB6YrY0BMh85" alt="Image" width="800" height="344" loading="lazy">
<em>Stuff might get verbose…</em></p>
<p>Notice we have progressed from the original single line to the full nine lines of code which we have to read and understand when we want to fix a bug or add a new feature.</p>
<blockquote>
<p>Stuff might get even more complex when combined with more complex generic Typescript types, which can make the whole code block even more mysterious (and hence waste more of our time).</p>
</blockquote>
<h3 id="heading-recapitulation">Recapitulation</h3>
<ol>
<li>The <code>.subscribe()</code> method accepts both the observer object and inline handlers.</li>
<li>The observer object represents the most versatile and concise way to subscribe to an observable stream.</li>
<li>In case we want to go with the inline subscribe arguments (<code>next</code>, <code>error</code>, <code>complete</code>) we can provide <code>null</code> in place of a handler we don’t need.</li>
<li>We should make sure that we don’t try to repeat the <code>.subscribe()</code> pattern when dealing with <code>.pipe()</code> and operators.</li>
<li>Always strive to keep the code as simple as possible and remove unnecessary redundancies!</li>
</ol>
<h4 id="heading-thats-it">That’s it! ✨</h4>
<blockquote>
<p>I hope you enjoyed this article and will now have better understanding of how to subscribe to RxJs observables with clean, concise implementation!</p>
</blockquote>
<p>Please support this guide with your ??? using the clap button and help it spread to a wider audience ? Also, don’t hesitate to ping me if you have any questions using the article responses or Twitter DMs @tom<a target="_blank" href="https://twitter.com/tomastrajan">astrajan.</a></p>
<blockquote>
<p><a target="_blank" href="https://twitter.com/tomastrajan">And never forget, the future is bright</a></p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/HDE38gYVRZf0lweAmygW6hc5yW3sHdp3agm9" alt="Image" width="800" height="533" loading="lazy">
_[avier Coiffic)](https://twitter.com/tomastrajan" rel="noopener" target="_blank" title=""&gt;Obviously the bright future! (? by X&lt;a href="https://unsplash.com/photos/WV4B_aVj0aQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<blockquote>
<p>Starting an Angular project? Check out <a target="_blank" href="https://github.com/tomastrajan/angular-ngrx-material-starter">Angular NgRx Material Starter</a>!</p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/mWKbDXFT-UMK-sCaFd9yMEVZstrY1roIHN7v" alt="Image" width="800" height="154" loading="lazy">
<em>Angular NgRx Material Starter with built in best practices, theming and much more!</em></p>
<p>If you made it this far, feel free to check out some of my other articles about Angular and frontend software development in general…</p>
<p><a target="_blank" href="https://hackernoon.com/%EF%B8%8F-the-7-pro-tips-to-get-productive-with-angular-cli-schematics-b59783704c54"><strong>?‍?️ The 7 Pro Tips To Get Productive With Angular CLI &amp; Schematics ?</strong></a><br><a target="_blank" href="https://hackernoon.com/%EF%B8%8F-the-7-pro-tips-to-get-productive-with-angular-cli-schematics-b59783704c54"><strong>An</strong>g_ular Schematics is a workflow tool for the modern web — official introduction articlehac_kernoon.com</a>  <a target="_blank" href="https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0"><strong>The Best Way To Unsubscribe RxJS Observable In The Angular Applications!</strong></a><br><a target="_blank" href="https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0">_There are many different ways how to handle RxJS subscriptions in Angular applications and we’re going to explore their…_blog.angularindepth.com</a><a target="_blank" href="https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f"><strong>Total Guide To Angular 6+ Dependency Injection — providedIn vs providers:[ ] ?</strong></a><br><a target="_blank" href="https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f">L_et’s learn when and how to use new better Angular 6+ dependency injection mechanism with new providedIn syntax to make…m_edium.com</a> <a target="_blank" href="https://blog.angularindepth.com/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794"><strong>The Ultimate Answer To The Very Common Angular Question: subscribe() vs | async Pipe</strong></a><br><a target="_blank" href="https://blog.angularindepth.com/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794">_Most of the popular Angular state management libraries like NgRx expose application state in a form of a stream of…_blog.angularindepth.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to build a simple & customizable web scraper using RxJS and Node ]]>
                </title>
                <description>
                    <![CDATA[ By Jacob Goh Introduction After getting to know RxJS (thanks to Angular!), I realized that it’s surprisingly a good fit for handling web scraping operations. I tried it out in a side project and I would like to share my experience with you. Hopefully... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-simple-customizable-web-scraper-using-rxjs-and-node-6858cfe82a39/</link>
                <guid isPermaLink="false">66c34fe59972b7c5c7624eb8</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web scraping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Nov 2018 02:10:34 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*zqqImyUXrCGM9nA-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jacob Goh</p>
<h3 id="heading-introduction">Introduction</h3>
<p>After getting to know RxJS (thanks to Angular!), I realized that it’s surprisingly a good fit for handling web scraping operations.</p>
<p>I tried it out in a side project and I would like to share my experience with you. Hopefully, this will open your eyes to how reactive programming can make your life simpler.</p>
<p>The codes can be found on <a target="_blank" href="https://github.com/jacobgoh101/web-scraping-with-rxjs">https://github.com/jacobgoh101/web-scraping-with-rxjs</a></p>
<h3 id="heading-requirements">Requirements</h3>
<ul>
<li>Node</li>
<li>RxJS and intermediate understanding of it</li>
<li><a target="_blank" href="https://www.npmjs.com/package/cheerio">cheerio</a>: it allows you to use jQuery-like syntax to extract information out of HTML code</li>
<li><a target="_blank" href="https://www.npmjs.com/package/request-promise-native">request-promise-native</a>: for sending HTTP request</li>
</ul>
<h3 id="heading-hypothetical-goal">Hypothetical Goal</h3>
<p>Everybody loves a good comedy movie.</p>
<p>Let’s make it our goal to scrape a list of good comedy movies from IMDB.</p>
<p>There are only 3 requirements that the target data needs to fulfill:</p>
<ul>
<li>it is a movie (not TV shows, music videos, etc)</li>
<li>it is a comedy</li>
<li>it has a rating of 7 or higher</li>
</ul>
<h3 id="heading-get-started">Get Started</h3>
<p>Let’s set our base URL and define a BehaviorSubject <code>allUrl$</code> that uses the base URL as the initial value.</p>
<p>(A BehaviorSubject is a <a target="_blank" href="https://www.youtube.com/watch?v=rdK92pf3abs">subject</a> with an initial value.)</p>
<pre><code><span class="hljs-keyword">const</span> { BehaviorSubject } =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'rxjs'</span>);<span class="hljs-keyword">const</span>  baseUrl  =  <span class="hljs-string">`https://imdb.com`</span>;<span class="hljs-keyword">const</span>  allUrl$  =  <span class="hljs-keyword">new</span>  BehaviorSubject(baseUrl);
</code></pre><p><code>allUrl$</code> is going to be the starting point of all crawling operations. Every URL will be passed into <code>allUrl$</code> and be processed on later.</p>
<h4 id="heading-making-sure-that-we-scrape-each-url-only-once">Making sure that we scrape each URL only once</h4>
<p>With the help of <a target="_blank" href="https://rxjs-dev.firebaseapp.com/api/operators/distinct">distinct</a> operators and <a target="_blank" href="https://www.npmjs.com/package/normalize-url">normalize-url</a>, we can easily make sure that we never scrape the same URL twice.</p>
<pre><code><span class="hljs-comment">// ...const { map, distinct, filter } =  require('rxjs/operators');const  normalizeUrl  =  require('normalize-url');</span>
</code></pre><pre><code><span class="hljs-comment">// ...</span>
</code></pre><pre><code><span class="hljs-keyword">const</span>  uniqueUrl$  =  allUrl$.pipe(    <span class="hljs-comment">// only crawl IMDB url    filter(url  =&gt;  url.includes(baseUrl)),    // normalize url for comparison    map(url  =&gt;  normalizeUrl(url, { removeQueryParameters: ['ref', 'ref_']     })),    // distinct is a RxJS operator that filters out duplicated values    distinct());</span>
</code></pre><h4 id="heading-its-time-to-start-scraping">It’s time to start scraping</h4>
<p>We are going to make a request to each unique URL and map the content of each URL into another observable.</p>
<p>To do that, we use <a target="_blank" href="https://www.learnrxjs.io/operators/transformation/mergemap.html">mergeMap</a> to map the result of the request to another observable.</p>
<pre><code><span class="hljs-keyword">const</span> { BehaviorSubject, <span class="hljs-keyword">from</span> } =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'rxjs'</span>);<span class="hljs-keyword">const</span> { map, distinct, filter, mergeMap } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'rxjs/operators'</span>);<span class="hljs-keyword">const</span> rp = <span class="hljs-built_in">require</span>(<span class="hljs-string">'request-promise-native'</span>);<span class="hljs-keyword">const</span>  cheerio  =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'cheerio'</span>);
</code></pre><pre><code><span class="hljs-comment">//...const urlAndDOM$ = uniqueUrl$.pipe(  mergeMap(url =&gt; {    return from(rp(url)).pipe(      // get the cheerio function $      map(html =&gt; cheerio.load(html)),      // add URL to the result. It will be used later for crawling      map($ =&gt; ({        $,        url      }))    );  }));</span>
</code></pre><p><code>urlAndDOM$</code> will emit an object consisting of 2 properties, which are <code>$</code> and <code>url</code>. <code>$</code> is a Cheerio function where you can use something like <code>$('div').text()</code> to extract information out of raw HTML code.</p>
<h4 id="heading-crawl-all-the-urls">Crawl all the URLs</h4>
<pre><code><span class="hljs-keyword">const</span> { resolve } =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'url'</span>);<span class="hljs-comment">//...</span>
</code></pre><pre><code><span class="hljs-comment">// get all the next crawlable URLsurlAndDOM$.subscribe(({ url, $ }) =&gt; {  $('a').each(function(i, elem) {    const href = $(this).attr('href');    if (!href) return;</span>
</code></pre><pre><code><span class="hljs-comment">// build the absolute url    const absoluteUrl = resolve(url, href);    allUrl$.next(absoluteUrl);  });});</span>
</code></pre><p>In the code above, we scrape all the links inside the page and send them to <code>allUrl$</code> to be crawled later.</p>
<h4 id="heading-scrape-and-save-the-movies-we-want">Scrape and save the movies we want!</h4>
<pre><code><span class="hljs-keyword">const</span>  fs  =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);<span class="hljs-comment">//...</span>
</code></pre><pre><code><span class="hljs-keyword">const</span> isMovie = $ =&gt;  $(<span class="hljs-string">`[property='og:type']`</span>).attr(<span class="hljs-string">'content'</span>) === <span class="hljs-string">'video.movie'</span>;<span class="hljs-keyword">const</span> isComedy = $ =&gt;  $(<span class="hljs-string">`.title_wrapper .subtext`</span>)    .text()    .includes(<span class="hljs-string">'Comedy'</span>);<span class="hljs-keyword">const</span> isHighlyRated = $ =&gt; +$(<span class="hljs-string">`[itemprop="ratingValue"]`</span>).text() &gt; <span class="hljs-number">7</span>;
</code></pre><pre><code>urlAndDOM$  .pipe(    filter(<span class="hljs-function">(<span class="hljs-params">{ $ }</span>) =&gt;</span> isMovie($)),    filter(<span class="hljs-function">(<span class="hljs-params">{ $ }</span>) =&gt;</span> isComedy($)),    filter(<span class="hljs-function">(<span class="hljs-params">{ $ }</span>) =&gt;</span> isHighlyRated($))  )  .subscribe(<span class="hljs-function">(<span class="hljs-params">{ url, $ }</span>) =&gt;</span> {    <span class="hljs-comment">// append the data we want to a file named "comedy.txt"    fs.appendFile('comedy.txt', `${url}, ${$('title').text()}\n`);  });</span>
</code></pre><h3 id="heading-yup-we-just-created-a-web-scraper">Yup, we just created a web scraper</h3>
<p>In around 70 lines of code, we have created a web scraper that</p>
<ul>
<li>automatically crawled URLs without unnecessary duplicates</li>
<li>automatically scrapes and saves the info we want in a text file</li>
</ul>
<p>You may see the code up to this point in <a target="_blank" href="https://github.com/jacobgoh101/web-scraping-with-rxjs/blob/86ff05e893dec5f1b39647350cb0f74efe258c86/index.js">https://github.com/jacobgoh101/web-scraping-with-rxjs/blob/86ff05e893dec5f1b39647350cb0f74efe258c86/index.js</a></p>
<p>If you have ever tried writing a web scraper from scratch, you should be able to see now how elegant it is to write one with RxJS.</p>
<h3 id="heading-but-we-are-not-done-yet">But we are not done yet…</h3>
<p>In an ideal world, the code above should work forever without any problems.</p>
<p>But in reality, silly errors happen.</p>
<h3 id="heading-handling-errors">Handling Errors</h3>
<h4 id="heading-limit-the-number-of-active-concurrent-connections">Limit the number of active concurrent connections</h4>
<p>If we send too many requests to a server in a short period of time, it’s likely that our IP will be temporarily blocked from making any further requests, especially for an established website like IMDB.</p>
<p>It’s also considered <strong>rude/unethical</strong> to send so many requests at once because it would create a heavier load on the server and in some cases, <strong>crash the server</strong>.</p>
<p><a target="_blank" href="https://www.learnrxjs.io/operators/transformation/mergemap.html">mergeMap</a> has built-in functionality to control concurrency. Simply add a number to the 3rd function argument and it will limit the active concurrent connection automatically. Graceful!</p>
<pre><code><span class="hljs-keyword">const</span> maxConcurrentReq = <span class="hljs-number">10</span>;<span class="hljs-comment">//...const urlAndDOM$ = uniqueUrl$.pipe(  mergeMap(    //...    null,    maxConcurrentReq  ));</span>
</code></pre><p>Code Diff: <a target="_blank" href="https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/6aaed6dae230d2dde1493f1b6d78282ce2e8f316">https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/6aaed6dae230d2dde1493f1b6d78282ce2e8f316</a></p>
<h4 id="heading-handle-and-retry-failed-request">Handle and Retry Failed Request</h4>
<p>Requests may fail randomly due to dead links or server-side rate limiting. This is crucial for web scrapers.</p>
<p>We can use <a target="_blank" href="https://www.learnrxjs.io/operators/error_handling/catch.html">catchError</a>, <a target="_blank" href="https://www.learnrxjs.io/operators/error_handling/retry.html">retry</a> operators to handle this.</p>
<pre><code><span class="hljs-keyword">const</span> { BehaviorSubject, <span class="hljs-keyword">from</span>, <span class="hljs-keyword">of</span> } =  <span class="hljs-built_in">require</span>(<span class="hljs-string">'rxjs'</span>);<span class="hljs-keyword">const</span> {  <span class="hljs-comment">// ...  retry,  catchError} = require('rxjs/operators');//...</span>
</code></pre><pre><code><span class="hljs-keyword">const</span> maxRetries = <span class="hljs-number">5</span>;<span class="hljs-comment">// ...</span>
</code></pre><pre><code><span class="hljs-keyword">const</span> urlAndDOM$ = uniqueUrl$.pipe(  mergeMap(    <span class="hljs-function"><span class="hljs-params">url</span> =&gt;</span> {      <span class="hljs-keyword">return</span> <span class="hljs-keyword">from</span>(rp(url)).pipe(        retry(maxRetries),        catchError(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {          <span class="hljs-keyword">const</span> { uri } = error.options;          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error requesting <span class="hljs-subst">${uri}</span> after <span class="hljs-subst">${maxRetries}</span> retries.`</span>);          <span class="hljs-comment">// return null on error          return of(null);        }),        // filter out errors        filter(v =&gt; v),        // ...      );    },</span>
</code></pre><p>Code Diff: <a target="_blank" href="https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/3098b48ca91a59aa5171bc2aa9c17801e769fcbb">https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/3098b48ca91a59aa5171bc2aa9c17801e769fcbb</a></p>
<h4 id="heading-improved-retry-failed-request">Improved Retry Failed Request</h4>
<p>Using retry operator, the retry would happen immediately after the request failed. This is not ideal.</p>
<p>It’s better to retry after a certain period of delay.</p>
<p>We can use the <code>genericRetryStrategy</code> suggested in <a target="_blank" href="https://www.learnrxjs.io/operators/error_handling/retrywhen.html">learnrxjs</a> to achieve this.</p>
<p>Code Diff: <a target="_blank" href="https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/e194f4ff128a573241055ffc0d1969d54ca8c270">https://github.com/jacobgoh101/web-scraping-with-rxjs/commit/e194f4ff128a573241055ffc0d1969d54ca8c270</a></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>To recap, in this post, we discussed:</p>
<ul>
<li>how to crawl a web page using Cheerio</li>
<li>how to avoid duplicated crawl using RxJS operators like filter, distinct</li>
<li>how to use mergeMap to create an observable of request’s response</li>
<li>how to limit concurrency in mergeMap</li>
<li>how to handle error</li>
<li>how to handle retry</li>
</ul>
<p>I hope this has been helpful to you and has deepened your understanding of RxJs and web scraping.</p>
<p><em>Originally published at <a target="_blank" href="https://dev.to/jacobgoh101/simple--customizable-web-scraper-using-rxjs-and-node-1on7">dev.to</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to build a reactive Joystick as a single RxJS Observable stream ]]>
                </title>
                <description>
                    <![CDATA[ By Henri Little - Beyle We are all likely familiar with the concept of a Joystick. We start holding the handle of the Joystick, we move the handle around, and when we release it, the handle gently goes back to its initial position. Now, what if we wa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/https-medium-com-henry-little-a-reactive-joystick-built-with-rxjs-abfca3668786/</link>
                <guid isPermaLink="false">66c357137ef110ecbf367b01</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 08 Oct 2018 15:07:23 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*X3xtviyY779db4yRZugTmg.gif" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Henri Little - Beyle</p>
<p>We are all likely familiar with the concept of a Joystick.</p>
<p>We start holding the handle of the Joystick, we move the handle around, and when we release it, the handle gently goes back to its initial position.</p>
<p>Now, what if we want to build some sort of software component that simulates the behaviour of a Joystick in the browser?</p>
<p>Well, with RxJS this turns out to be pretty simple. And it is also an interesting exercise to prove your Reactive thinking. You can jump directly to the code <a target="_blank" href="https://github.com/EnricoPicci/reactive-joystick">here</a> if you want, otherwise keep reading and see what we can do.</p>
<h3 id="heading-which-are-the-events-we-are-interested-in">Which are the events we are interested in?</h3>
<p>The behaviour of the Joystick can be seen a series of events combined together in some way.</p>
<p>The first event we are interested in is when the user presses a mouse on the handle (<code>mousedown</code>) - the handle is just the central part of the Joystick image.</p>
<p>If you hold the mouse pressed, then you can move around and you see the handle move accordingly — the <code>mousemove</code> events of the mouse are therefore the second series of events we want to capture.</p>
<p>Last, we need to consider when the user releases the mouse (<code>mouseup</code>) since this is the event that causes the Joystick handle to go back to its initial position.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/nl-lPdU3SnW8QP6FtuGXwFhwftNOJvwzy2fF" alt="Image" width="800" height="108" loading="lazy">
<em>Relevant events for the Joystick case</em></p>
<p>The whole sequence can be repeated after the handle is released. The mouse is pressed on the handle, then it is moved, then it is released. Again and again.</p>
<p>This repetition can be seen as a stream of events. We can say that the behaviour of a joystick is governed by this stream of events.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PSeMoBEzyvtgqnNjQFIMNhKZBVk0UyhSr5Ii" alt="Image" width="800" height="64" loading="lazy">
<em>The stream of events of a Joystick</em></p>
<p>If we are able to build such stream of events, we are in a good position to reach our objective — that is, to implement a Joystick software component for the browser using RxJS.</p>
<h3 id="heading-the-building-blocks-with-rxjs">The building blocks with RxJS</h3>
<p>The browser actually provides us with the notification of the events we are interested in: the <code>mousedown</code> event on the DOM element representing the handle of the Joystick, and the <code>mousemove</code> and <code>mouseup</code> events at DOM document level.</p>
<p>RxJS, on its side, comes with the function <code>fromEvent</code> that allows us to create an Observable from a browser event.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/E5gArW8EsLVN47YdlzZQDfsr-J-v7wRYha2w" alt="Image" width="800" height="313" loading="lazy">
<em>Create an Observable with <code>fromEvent</code> RxJS function</em></p>
<p>Using this mechanism we can create the three streams of events which are going to be the building blocks of our solution: <strong>mouse_DOWN_Obs</strong>, <strong>mouse_MOVE_Obs</strong>, <strong>mouse_UP_Obs</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/18oYzRw8TkzIoscKyhouvoJEe08erjL0cnfL" alt="Image" width="800" height="274" loading="lazy">
<em>The streams of events which are our building blocks</em></p>
<p>But these are just our building blocks. We need to do something with them in order to get what we want: we need to ignore all <code>mousemove</code> events which occur before the first <code>mousedown</code> and then ignore all the <code>mousemove</code> events which occur after the next <code>mouseup</code>. Then we repeat all this again when a new <code>mousedown</code> event occurs. These compose the <strong>“stream of events for the Joystick”</strong><em>.</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/57-sjEw-zvOm53BVKUeUh9KaC55f7ytcUHA-" alt="Image" width="800" height="362" loading="lazy">
<em>Joystick event stream built from building blocks</em></p>
<h3 id="heading-the-transformation-of-observables-via-composition-of-operators">The transformation of Observables via composition of operators</h3>
<p>Everything starts when the user presses the mouse on the handle of the Joystick, i.e. <strong>mouse_DOWN_Obs</strong>. We can call it the source Observable.</p>
<p>Once we are notified of an event from <strong>mouse_DOWN_Obs</strong> we have to <em>switch</em> and start listening to <strong>mouse_MOVE_Obs.</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/s3esbte2H8imrlxNz2pHYtOGaXC7NMYd-Ytt" alt="Image" width="800" height="302" loading="lazy">
<em>The first transformation with switchMap</em></p>
<p>It may seem like we have not achieved much, but in fact we are now in a position where we can <em>take</em> the <strong>mouse_MOVE_Obs</strong> notifications <em>until</em> we hear from <strong>mouse_UP_Obs</strong>. At this point we stop just to restart at the next notification from <strong>mouse_DOWN_Obs</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/zfSEa0bNUZx0i52yfZXkpg1-FqxBSGaREnJy" alt="Image" width="800" height="301" loading="lazy">
<em>The second transformation with takeUntil</em></p>
<p>Notice that we apply <code>takeUntil</code> to <strong>mouse_MOVE_Obs</strong>, because this is the Observable we want to complete. If we had applied one level higher, to <strong>mouse_DOWN_Obs</strong>, this is what would have happened:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZS1GyApmXIMmbSunvKPbVTBWGsJf1TZmS3FT" alt="Image" width="800" height="303" loading="lazy"></p>
<p>Just the first sequence of move events would have been notified, and then the stream of events would have been closed down. No more events for the Joystick.</p>
<h3 id="heading-now-is-the-time-of-side-effects">Now is the time of side effects</h3>
<p>We have learned how to build a stream of all the events relevant for a Joystick. To do something useful with this stream, we need to link the events to some sort of action we want to do. More specifically:</p>
<ul>
<li>when we sense a <code>mousemove</code> event we have to change the position of the handle on the browser</li>
<li>when we sense a <code>mouseup</code> event we have to gently move the handle back to its original position, setting some transition style</li>
<li>when we sense a <code>mousedown</code> event we have to reset the transition style</li>
</ul>
<p>But careful. Not all are <code>mousemove</code> events, not all are <code>mouseup</code> events, and not all are <code>mousedown</code> events. Only those which belong to the set of <strong>“relevant events for the Joystick”</strong><em>.</em> For instance, we are not interested in all <code>mousemove</code> events which happen before the Joystick has been activated (pressing the mouse on the handle) or after the Joystick handle has been released.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/jMq3dPUHgqbRRovbFLXCKmSG9XueC-dIMa0V" alt="Image" width="800" height="507" loading="lazy">
<em>Where we need side effects</em></p>
<p>Let’s get back to our main track of reasoning. We need to do something at the occurrence of some events. Something that changes the state of the system. In our case, this is the position of the handle on the browser. In <strong>functional</strong> programming terms these are called <strong>side effects</strong>, i.e. functions which change the state of the system.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/jHOP52U5BPDPSJOF2BLBvcHzCg6ZW7ZZ9m8J" alt="Image" width="800" height="497" loading="lazy">
<em>Side effects as functions — Functions as side effects</em></p>
<p>RxJS gives us two ways to implement <strong>side effects</strong>.</p>
<p>The first one is the <code>subscribe</code> method of Observable. The second one is the <code>tap</code> operator, formerly know as <code>do</code>, which <em>“performs a</em> <strong>side effect</strong> <em>for every emission on the source Observable, but returns an Observable that is identical to the source”</em> — the <strong><em>side effect</em></strong> is determined by the function passed to <code>tap</code> as a parameter. <code>tap</code> is the method we are going to use.</p>
<p>Eventually this is the core of the code that implements our Reactive Joystick</p>
<pre><code><span class="hljs-keyword">const</span> handle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"handle"</span>);<span class="hljs-keyword">const</span> mouse_DOWN_Obs = rxjs.fromEvent(handle, <span class="hljs-string">'mousedown'</span>);<span class="hljs-keyword">const</span> mouse_MOVE_Obs = rxjs.fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'mousemove'</span>);<span class="hljs-keyword">const</span> mouse_UP_Obs = rxjs.fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'mouseup'</span>);
</code></pre><pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">activateJoytick</span>(<span class="hljs-params"></span>) </span>{  mouse_DOWN_Obs.pipe(    rxjs.operators.tap(<span class="hljs-function">() =&gt;</span> joystickActivated()),    rxjs.operators.switchMap(<span class="hljs-function">() =&gt;</span> mouse_MOVE_Obs.pipe(      rxjs.operators.takeUntil(mouse_UP_Obs.pipe(        rxjs.operators.tap(<span class="hljs-function">() =&gt;</span> joystickReleased())      )),    )),    rxjs.operators.tap(<span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> showHandleInNewPosition(event))  )  .subscribe();}
</code></pre><h3 id="heading-example-code">Example code</h3>
<p>You can find the example code <a target="_blank" href="https://github.com/EnricoPicci/reactive-joystick">here</a>, where you can compare the RxJS implementation with one built using pure JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Go SUPER SAIYAN with RxJS Observables ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough I loved DragonBall Z as a kid, and still love it as an adult. Among the ludicrous number of transformations, the original Super Saiyan remains my favorite. Nothing quite like the original I’m also loving RxJS the more I level up... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/go-super-saiyan-with-rxjs-observables-d4681ae51930/</link>
                <guid isPermaLink="false">66d461913a8352b6c5a2ab30</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 17 Jul 2018 17:31:50 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*qE2wxzg_yiFOIN-Q" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p>I loved DragonBall Z as a kid, and still love it as an adult.</p>
<p>Among the ludicrous number of transformations, the original Super Saiyan remains my favorite.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*qE2wxzg_yiFOIN-Q" alt="0*qE2wxzg_yiFOIN-Q" width="333" height="500" loading="lazy"></p>
<blockquote>
<p>Nothing quite like the original</p>
</blockquote>
<p>I’m also loving RxJS the more I level up with it, so why not combine these two for the ultimate showdown?</p>
<h3 id="heading-lets-go-super-saiyan">Let’s Go Super Saiyan</h3>
<p>With four sprite sheets and a bit of HTML, CSS, and RxJS, we can recreate this legendary transformation!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qgex4ns9jPE_tpCy_OTfWA.gif" alt="1*qgex4ns9jPE_tpCy_OTfWA" width="600" height="563" loading="lazy"></p>
<p>This is what we’ll be making. Exciting, right?! ?</p>
<h3 id="heading-setup">Setup</h3>
<p>Everything’s on <a target="_blank" href="https://github.com/yazeedb/dbz-rxjs">my GitHub</a>.</p>
<pre><code>cd ./wherever-you-want
git clone [https:<span class="hljs-comment">//github.com/yazeedb/dbz-rxjs](https://github.com/yazeedb/dbz-rxjs)</span>
cd dbz-rxjs
</code></pre><p>Open <code>index.html</code> in your favorite browser, and the project in your favorite text editor, and you’re ready to go!</p>
<p>No <code>npm install</code>s today ?</p>
<p>And going forward, I’ll use the acronym “SSJ” instead of “Super Saiyan” for brevity.</p>
<h3 id="heading-first-day-of-training">First Day of Training</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*FpxB4WdbNMmldqZDnpVp1g.png" alt="1*FpxB4WdbNMmldqZDnpVp1g" width="860" height="666" loading="lazy"></p>
<p>You’ll notice that Goku’s already moving. Since we’re focusing on RxJS, we’ll just skim the project’s starting point.</p>
<p>Here’s the main HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"meter-container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hold any key to POWER UP!<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"meter"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sprite"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"base"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The bottom <code>div</code> has <code>class="base"</code>, which corresponds to this CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.base</span>,
<span class="hljs-selector-class">.ssj</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">120px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">250px</span>;
  <span class="hljs-attribute">animation</span>: stand <span class="hljs-number">0.8s</span> <span class="hljs-built_in">steps</span>(<span class="hljs-number">2</span>) infinite;
}

<span class="hljs-selector-class">.base</span> {
  <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">'img/goku-standing-sheet.png'</span>);
}
</code></pre>
<p>This sets Goku’s width, height, and standing animation.</p>
<p>If you look at his base/ssj sprite sheets, it’s two different positions and we’re switching between them every 0.8 seconds.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Cy1fArcSxNJwGDc98YMHEA.png" alt="1*Cy1fArcSxNJwGDc98YMHEA" width="250" height="227" loading="lazy"><img src="https://cdn-media-1.freecodecamp.org/images/1*mNVDs7NKfcfkA8l86IxOTA.png" alt="1*mNVDs7NKfcfkA8l86IxOTA" width="250" height="227" loading="lazy"></p>
<p>The switching’s handled towards the bottom of <code>style.css</code>:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> stand {
  <span class="hljs-selector-tag">from</span> {
    <span class="hljs-attribute">background-position</span>: <span class="hljs-number">0px</span>;
  }
  <span class="hljs-selector-tag">to</span> {
    <span class="hljs-attribute">background-position</span>: -<span class="hljs-number">255px</span>;
  }
}
</code></pre>
<p>Same thing for power up:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sSTHMTvkazP0BaZPubo4kg.png" alt="1*sSTHMTvkazP0BaZPubo4kg" width="500" height="266" loading="lazy"><img src="https://cdn-media-1.freecodecamp.org/images/1*xkI3tsGLGRpVoH2RjaFK9w.png" alt="1*xkI3tsGLGRpVoH2RjaFK9w" width="500" height="267" loading="lazy"></p>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> powerup {
  <span class="hljs-selector-tag">from</span> {
    <span class="hljs-attribute">background-position</span>: <span class="hljs-number">0px</span>;
  }
  <span class="hljs-selector-tag">to</span> {
    <span class="hljs-attribute">background-position</span>: -<span class="hljs-number">513px</span>;
  }
}
</code></pre>
<p>We’ll cover the power up meter when we manipulate it.</p>
<h3 id="heading-mastering-the-dom-elements">Mastering the DOM Elements</h3>
<p><code>index.html</code> already includes <code>RxJS@6.2.1</code> via CDN, so you’re covered.</p>
<p>In <code>app.js</code>, let’s capture the DOM elements we’re interested in:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sprite = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#sprite'</span>);
<span class="hljs-keyword">const</span> meterContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#meter-container'</span>);
<span class="hljs-keyword">const</span> meter = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#meter'</span>);
</code></pre>
<p>I prefer to alias <code>document.querySelector</code> so using it doesn’t cause me wrist pain.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> $ = <span class="hljs-built_in">document</span>.querySelector.bind(<span class="hljs-built_in">document</span>);**
<span class="hljs-keyword">const</span> sprite = $(<span class="hljs-string">'#sprite'</span>);
<span class="hljs-keyword">const</span> meterContainer = $(<span class="hljs-string">'#meter-container'</span>);
<span class="hljs-keyword">const</span> meter = $(<span class="hljs-string">'#meter'</span>);
</code></pre>
<p>Next, we’ll create a <code>main</code> function and immediately call it.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ...</span>

<span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// do something</span>
};
main();
</code></pre>
<h3 id="heading-powering-up">Powering Up</h3>
<p>Here is <code>main</code>’s first code snippet:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { fromEvent } = rxjs;

  <span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
  <span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);
};
</code></pre>
<p>Goku should power up when a key is held down, and stop when that key is let go. We can use the <code>fromEvent</code> operator to create two observables:</p>
<ul>
<li><code>begin</code>: Notifies when the user presses a key <strong>down</strong>.</li>
<li><code>end</code>: Notifies whenever the user <strong>lets go</strong> of a key.</li>
</ul>
<p>Then we can <strong>subscribe</strong> to these emissions and act upon them. To get the power up animation, give <code>sprite</code> the <code>powerup</code> class name.</p>
<pre><code class="lang-js">begin.subscribe(<span class="hljs-function">() =&gt;</span> {
  sprite.classList.add(<span class="hljs-string">'powerup'</span>);
});
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*6-GLDooG9dTyGqNQ2XP0ww.png" alt="1*6-GLDooG9dTyGqNQ2XP0ww" width="856" height="618" loading="lazy"></p>
<p>It works, but pressing a key causes him to power up forever…</p>
<p>We must also subscribe to the <code>end</code> observable, so we know when the key has been let go.</p>
<pre><code class="lang-js">end.subscribe(<span class="hljs-function">() =&gt;</span> {
  sprite.classList.remove(<span class="hljs-string">'powerup'</span>);
});
</code></pre>
<p>Now he powers up and down at your command.</p>
<h3 id="heading-building-a-scouter">Building a Scouter</h3>
<p>Any DBZ fan has seen a scouter, the little eyewear used to track power levels (until like episode 20…).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*8H9CSUZbfDPxmdgR.png" alt="0*8H9CSUZbfDPxmdgR" width="816" height="506" loading="lazy"></p>
<blockquote>
<p>Obligatory &gt; 9000 joke</p>
</blockquote>
<p>As Saiyans power up, their power level grows. Inconceivable, right?</p>
<p>We need a way to track Goku’s power level as he ascends, and trigger the SSJ transformation after say, 100 points.</p>
<p>We can start his power off at 1, and increase it while the user holds a key down.</p>
<h4 id="heading-rxjs-operators">RxJS Operators</h4>
<p>Operators are where RxJS really shines. We can use pure functions to describe how data should transform through the stream.</p>
<p>When the user holds a key down, let’s transform those emissions into a number that increases over time.</p>
<h4 id="heading-scan">Scan</h4>
<p>The <a target="_blank" href="https://www.learnrxjs.io/operators/transformation/scan.html">scan operator</a> is perfect for this. It’s like <code>Array.reduce</code>, but it emits <strong>as it’s reducing</strong>.</p>
<p>For example, if you have an array of numbers:</p>
<pre><code class="lang-js">nums = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
</code></pre>
<p>And wish to add them up, <code>reduce</code> is a great choice.</p>
<pre><code class="lang-js">nums.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>);
<span class="hljs-comment">// 15</span>
</code></pre>
<p>What if you want to see each addition as it happens?</p>
<p>Enter <code>scan</code>. You can run this in our app’s console.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span> } = rxjs;
<span class="hljs-keyword">const</span> { scan } = rxjs.operators;

<span class="hljs-keyword">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>])
  .pipe(scan(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>))
  .subscribe(<span class="hljs-built_in">console</span>.log);

<span class="hljs-comment">// 1 (0 + 1)</span>
<span class="hljs-comment">// 3 (1 + 2)</span>
<span class="hljs-comment">// 6 (3 + 3)</span>
<span class="hljs-comment">// 10 (6 + 4)</span>
<span class="hljs-comment">// 15 (10 + 5)</span>
</code></pre>
<p>See how the emissions increase over time? We can do that with Goku as he powers up!</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { fromEvent } = rxjs;
<span class="hljs-keyword">const</span> { scan, tap } = rxjs.operators;

<span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
<span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);

begin
  .pipe(
    scan(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level + <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
    tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log({ level });
    })
  )
  .subscribe(<span class="hljs-function">() =&gt;</span> {
    sprite.classList.add(<span class="hljs-string">'powerup'</span>);
  });
</code></pre>
<p>We start his level at <code>1</code> and increase it by 1 every time the <code>keydown</code> event fires.</p>
<p>And the <a target="_blank" href="https://www.learnrxjs.io/operators/utility/do.html">tap operator</a> operator lets us quickly log the value without disturbing the pipeline.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*CviOotpl-fpRm5qrI7INhQ.png" alt="1*CviOotpl-fpRm5qrI7INhQ" width="1600" height="859" loading="lazy"></p>
<blockquote>
<p>My power infinitely approaches MAXIMUM!</p>
</blockquote>
<h3 id="heading-going-super-saiyan">Going Super Saiyan</h3>
<p>We’ve trained hard, it’s time to transform.</p>
<p>The <code>scan</code> operator tracks Goku’s power level. Now we need to go SSJ when it emits 100.</p>
<p>I built a map of <code>levels: transformations</code>. You can put it right above <code>main</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> powerLevels = {
  <span class="hljs-number">100</span>: {
    <span class="hljs-attr">current</span>: <span class="hljs-string">'base'</span>,
    <span class="hljs-attr">next</span>: <span class="hljs-string">'ssj'</span>
  }
};

<span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// ...</span>
};
</code></pre>
<p>It’s overkill, but should simplify adding future transformations.</p>
<p>When the power level reaches a number in that <code>powerLevels</code> map, we’ll remove its <code>current</code> class from <code>sprite</code> and add the <code>next</code> class.</p>
<p>This lets us smoothly go from one transformation to the next.</p>
<p>Here’s the code.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { fromEvent } = rxjs;
<span class="hljs-keyword">const</span> { filter, map, scan, tap } = rxjs.operators;

<span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
<span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);

begin
  .pipe(
    scan(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level + <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
    tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log({ level });
      sprite.classList.add(<span class="hljs-string">'powerup'</span>);
    }),
    map(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> powerLevels[level]),
    filter(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level &amp;&amp; level.next)
  )
  .subscribe(<span class="hljs-function">(<span class="hljs-params">{ current, next }</span>) =&gt;</span> {
    sprite.classList.remove(current);
    sprite.classList.add(next);
  });
</code></pre>
<h4 id="heading-map-and-filter">Map and Filter</h4>
<p>Adding the <code>powerup</code> class now happens inside of <code>tap</code>, because it should always happen. The SSJ transformation however, <strong>shouldn’t</strong> always happen.</p>
<p>Using <code>map</code>, the latest power level becomes an entry in the <code>powerLevels</code> map. We use <code>filter</code> to check if the entry exists <strong>and</strong> has a <code>.next</code> property.</p>
<p>If it does, that means Goku can go even further beyond! Our <code>.subscribe</code> will swap <code>current</code> and <code>next</code> as class names on <code>sprite</code>.</p>
<p>The end result?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*q-ifHhrr8byMWPENjBpNyQ.gif" alt="1*q-ifHhrr8byMWPENjBpNyQ" width="600" height="411" loading="lazy"></p>
<h3 id="heading-power-meter">Power Meter</h3>
<p>You’re having as much fun as I am, right? Unfortunately, our user won’t.</p>
<p>They can’t see how high Goku’s power level is! They won’t know how to open the DevTools console. We must remedy this!</p>
<p>Let’s improve our UX by filling the power meter. You can put this above <code>main</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fillMeter = <span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> limit = <span class="hljs-number">100</span>;

  <span class="hljs-keyword">if</span> (level &gt;= limit) {
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">const</span> containerWidth = meterContainer.offsetWidth;
  <span class="hljs-keyword">const</span> newWidth = (level / limit) * containerWidth;

  meter.style.width = <span class="hljs-string">`<span class="hljs-subst">${newWidth}</span>px`</span>;
};
</code></pre>
<p>And call it inside <code>tap</code>.</p>
<pre><code class="lang-js">tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log({ level });
  sprite.classList.add(<span class="hljs-string">'powerup'</span>);
  fillMeter(level);
});
</code></pre>
<p>And here we go:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qvr0L_5cmXzMI4g8sYtoyg.gif" alt="1*qvr0L_5cmXzMI4g8sYtoyg" width="600" height="318" loading="lazy"></p>
<h3 id="heading-going-even-further-beyond">Going Even Further Beyond</h3>
<p>Unlocking more transformations is just a matter of adding sprites, and updating our <code>powerLevels</code> map. If you’re interested, submit a PR on <a target="_blank" href="https://github.com/yazeedb/dbz-rxjs">the repo</a> and we’ll definitely talk.</p>
<p>Here’s the <a target="_blank" href="https://www.deviantart.com/bruguii/art/goku-fin-jus-268665173">original sprite sheet</a>. Enjoy!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to design a distributed system that controls object animation using RxJx, Node, and WebSockets ]]>
                </title>
                <description>
                    <![CDATA[ By Enrico Piccinin In my previous article, How to think reactively and animate moving objects using RxJs, I described how to build a MobileObject class that simulates the movement of an object subject to accelerations imposed on it by an external con... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/reactive-thinking-how-to-design-a-distributed-system-with-rxjs-websockets-and-node-57d772f89260/</link>
                <guid isPermaLink="false">66d4608c3a8352b6c5a2aad1</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jun 2018 18:59:27 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*nrD86pjtZh_Xjn9AJZKLRQ.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Enrico Piccinin</p>
<p>In my previous article, <a target="_blank" href="https://medium.freecodecamp.org/thinking-reactively-how-to-animate-with-movement-objects-using-rxjs-692518b6f2ac">How to think reactively and animate moving objects using RxJs</a>, I described how to build a <strong>MobileObject</strong> class that simulates the movement of an object subject to accelerations imposed on it by an external controller.</p>
<p>Now I want to show you a simple distributed system that allows a <strong>Controller</strong> app to remotely control the movement of a <strong>MobileObject.</strong> A second remote app, the <strong>Monitor</strong>, shows the movement of the object on a two-dimensional plan. At the center of the system lays a <strong>MobileObjectServer</strong>, which is the place where the <strong>MobileObjects</strong> live.</p>
<p>The goal of this article is to explain how Reactive thinking can progressively produce a design which maps the requirements very naturally and produces a neat solution. <strong>We will end up solving the problem subscribing to just ONE Observable</strong>.</p>
<p>We’ll focus on the server part, which is the most intriguing from this standpoint.</p>
<p>For the implementation, we’ll use RxJs and TypeScript. The server runs on Node. All the components communicate using Web-Sockets.</p>
<p>The full code base, comprised of the Server Controller and Monitor, can be found <a target="_blank" href="https://github.com/EnricoPicci/mobile-object-observables">here</a>.</p>
<h3 id="heading-schema-of-the-distributed-system">Schema of the distributed system</h3>
<p>The logical schema of the distributed system is represented in the following diagram:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*N6105oynT3__Doc_VreZhw.png" alt="Image" width="800" height="492" loading="lazy">
<em>Schema of the distributed system</em></p>
<p>At the center lays the <strong>MobileObjectServer</strong> where the instances of the <strong>MobileObjets</strong> run. Each <strong>MobileObject</strong> is controlled by its <strong>Controller</strong>, that is a Web app through which we can issue commands (like accelerate, brake) to the <strong>MobileObject</strong>. The movement of all <strong>MobileObjects</strong> can be seen on one or more <strong>Monitors</strong>. Each <strong>Monitor</strong> is again a Web app.</p>
<p>The following diagram shows a sample interaction flow between one <strong>Controller</strong>, one <strong>Monitor,</strong> and the <strong>MobileObjectServer</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*AMmLkEOKyV9vheNXM4F0fg.png" alt="Image" width="800" height="576" loading="lazy">
<em>Sample interaction flow</em></p>
<h3 id="heading-the-server-requirements-in-terms-of-events">The Server Requirements in terms of events</h3>
<p>We can express the requirements for the server part of our distributed system in terms of events:</p>
<ul>
<li><strong>Event1</strong> — when a <strong>Controller</strong> connects =&gt; create <strong>a MobileObj</strong>ect</li>
<li><strong>Event2</strong> — when a <strong>Controller</strong> receives a command =&gt; forward the command to t<strong>he MobileObj</strong>ect controlled by t<strong>he Control</strong>ler</li>
<li><strong>Event3</strong> — when a <strong>Controller</strong> disconnects =&gt; delete t<strong>he MobileObje</strong>ct controlled by t<strong>he Control</strong>ler</li>
<li><strong>Event4</strong> — when a <strong>Monitor</strong> connects =&gt; start sending dynamics data of all runni<strong>ng MobileObje</strong>cts to the newly connect<strong>ed Moni</strong>tor</li>
<li><strong>Event5</strong> — when a <strong>MobileObject</strong> is added =&gt; start sending its dynamics data to all t<strong>he Monito</strong>rs connected</li>
<li><strong>Event6</strong> — when a <strong>Monitor</strong> disconnects =&gt; stop sending the streams of dynamics data for a<strong>ll MobileObje</strong>cts to th<strong>at Moni</strong>tor</li>
</ul>
<p>Reactive thinking will produce a design which naturally maps the requirements expressed in this way.</p>
<h3 id="heading-the-elements-composing-the-server">The elements composing the server</h3>
<p>The server component of the distributed application is made up of two main elements:</p>
<ul>
<li>the <strong>MobileObject</strong> class, which implements the dynamic movement logic using RxJs Observables — this has been described in detail <a target="_blank" href="https://medium.freecodecamp.org/thinking-reactively-how-to-animate-with-movement-objects-using-rxjs-692518b6f2ac">here</a></li>
<li>the <strong>MobileObjectServer</strong> class<strong>,</strong> which manages the web-socket protocol, receiving commands from the <strong>Controller</strong> and sending out to the <strong>Monitors</strong> all information about the dynamics of <strong>MobileObject.</strong> This implementation has been inspired by <a target="_blank" href="https://medium.com/dailyjs/real-time-apps-with-typescript-integrating-web-sockets-node-angular-e2b57cbd1ec1?t=1&amp;cn=ZmxleGlibGVfcmVjcw%3D%3D&amp;refsrc=email&amp;iid=9b197a27b4a14948b1d2fd4ad999e0a1&amp;uid=39235406&amp;nid=244%20276893704">this article</a> from <a target="_blank" href="https://www.freecodecamp.org/news/reactive-thinking-how-to-design-a-distributed-system-with-rxjs-websockets-and-node-57d772f89260/undefined">Luis Aviles</a>.</li>
</ul>
<h4 id="heading-mobileobject-apis">MobileObject APIs</h4>
<p>Let’s have a brief overview of the <strong>MobileObject</strong> class — all details can be found <a target="_blank" href="https://medium.freecodecamp.org/thinking-reactively-how-to-animate-with-movement-objects-using-rxjs-692518b6f2ac">here</a> while the code can be found in <a target="_blank" href="https://github.com/EnricoPicci/mobile-object-observables">this repository</a>.</p>
<p>The <strong>MobileObject</strong> offers two families of APIs.</p>
<p>The first one is the set of methods through which an external <strong>Controller</strong> can issue commands that affect the dynamics of the object (for example, accelerate, brake).</p>
<p>The second are streams of readonly data which communicate to external clients, the <strong>Monitors</strong>, the relevant data about the dynamic behaviour of the object (that is, its position and velocity over time).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*fv6FyPHZ-6CifV96bFKUCg.png" alt="Image" width="800" height="190" loading="lazy">
<em>APIs of MobileObject</em></p>
<p>In order to move an instance of a <strong>MobileObject</strong>, a <strong>Controller</strong> has to turn it on (with the <code>turnOn()</code> method), apply the desired acceleration (with the methods <code>accelerateX(acc: number)</code> and <code>accelerateY(acc: number)</code>), and then maybe brake (with the method <code>brake()</code>).</p>
<p>When a <strong>Monitor</strong> connects to the <strong>MobileObjectServer</strong>, the <strong>MobileObjectServer</strong> subscribes to the <code>dynamicsObs</code> and the observable of the <strong>MobileObjects</strong> running in the server. It then starts sending the data related to their movement to the connected <strong>Monitors</strong>.</p>
<p>For the purpose of this article, this is all you need to know about the <strong>MobileObject</strong>.</p>
<h3 id="heading-sockets-as-observables">Sockets as Observables</h3>
<p>The <strong>MobileObjectServer</strong> starts doing something when a client, either a <strong>Controller</strong> or a <strong>Monitor</strong>, opens a websocket connection. Over the course of time, the <strong>MobileObjectServer</strong> can receive many requests to open a connection from many clients.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*z4I5iqA1BdVKuth770mqMw.png" alt="Image" width="800" height="145" loading="lazy">
<em>Sequence of sockets opened over time</em></p>
<p>This looks like an Observable of sockets. This is how to obtain it using the <code>socket.io</code> library:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Server } <span class="hljs-keyword">from</span> <span class="hljs-string">'http'</span>;

<span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
<span class="hljs-keyword">import</span> { Observer } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> socketIoServer <span class="hljs-keyword">from</span> <span class="hljs-string">'socket.io'</span>;

<span class="hljs-keyword">import</span> {SocketObs} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-obs'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sockets</span>(<span class="hljs-params">httpServer: Server, port</span>) </span>{
    httpServer.listen(port, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Running server on port %s'</span>, port);
    });
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Observable&lt;SocketObs&gt;(
        <span class="hljs-function">(<span class="hljs-params">subscriber: Observer&lt;SocketObs&gt;</span>) =&gt;</span> {
            socketIoServer(httpServer).on(<span class="hljs-string">'connect'</span>, 
                <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
                    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'client connected'</span>);
                    subscriber.next(<span class="hljs-keyword">new</span> SocketObs(socket));
                }
            );
        }
    );
}
</code></pre>
<p>Via the function <code>sockets</code>, we create an Observable of <code>SocketObs</code> (we will see the implementation of this class later). Any time the websocket server receives a <em>connect</em> request and creates a new <em>socket</em>, the Observable returned by this function emits an instance of <code>SocketObs</code> which wraps the <em>socket</em> just created.</p>
<h4 id="heading-messages-over-sockets-as-observables">Messages over sockets as Observables</h4>
<p>Sockets can be used to send messages from the client to the server and vice versa. With the <code>socket.io</code> library, we can send messages using the <code>emit</code> method.</p>
<p><code>SocketIO.Socket.emit(event: string, …args: any[]): SocketIO.Socket</code></p>
<p>The parameter <code>event</code> can be seen as an identifier of the type of message we want to send. The <code>…args</code> parameters can be used to send data specific to a single message.</p>
<p>Whoever is interested in a certain type of message (or event, to use the <code>socket.io</code> terminology) can start listening on the socket using the method <code>on</code>.</p>
<p><code>SocketIO.Emitter.on(event: string, fn: Function): SocketIO.Emitter</code></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*9dXtrny7FzljFxyS886iZg.png" alt="Image" width="800" height="543" loading="lazy">
<em>Sequence of messages received over time</em></p>
<p>Again, the sequences of messages received by the Receiver look like Observables. This is how we can create Observables that actually emit any time a message of a certain type is received.</p>
<p>The <code>onMessageType</code> method is the one that does the trick. It returns an Observable, which emits any time a message of type <code>messageType</code> is received.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Observable, Observer } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SocketObs</span> </span>{
    <span class="hljs-keyword">constructor</span>(private socket: SocketIO.Socket) {}

    onMessageType(messageType): Observable&lt;any&gt; {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Observable&lt;any&gt;(<span class="hljs-function">(<span class="hljs-params">observer: Observer&lt;any&gt;</span>) =&gt;</span> {
            <span class="hljs-built_in">this</span>.socket.on(messageType, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> observer.next(data));
        });
    }
}
</code></pre>
<p>In this way, sockets events, or messages as we call them here, have been transformed into Observables. These are going to be the foundations of our design.</p>
<h3 id="heading-determine-the-nature-of-the-client">Determine the nature of the Client</h3>
<p>There are two types of clients which can connect with the <strong>MobileObjectServer.</strong> One is the <strong>Controller</strong> and one is the <strong>Monitor</strong>. The <strong>MobileObjectServer</strong> first needs to determine which type of client it is going to deal with on a specific socket.</p>
<p>The way we have chosen to implement such logic is to have the <strong>Controller</strong> and the <strong>Monitor</strong> send different message types as their first message.</p>
<ul>
<li><strong>Controller</strong> sends a message of type BIND_CONTROLLER</li>
<li><strong>Monitor</strong> sends a message of type BIND_MONITOR</li>
</ul>
<p>Depending on the type of the first message received on a socket, the <strong>MobileObjectServer</strong> is able to identify whether it is communicating with a <strong>Controller</strong> or a <strong>Monitor</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*HYPnLICInzJl6nG6oRVFVw.png" alt="Image" width="800" height="420" loading="lazy">
<em>How to determine the nature of the client on a socket</em></p>
<p>As soon as a socket is created, the <strong>MobileObjectServer</strong> has to start listening to both types of messages, BIND_CONTROLLER and BIND_MONITOR. The first to occur will win. It is a <code>race</code> between the two Observables which map the two different types of messages.</p>
<p>Such logic has to be repeated any time a new socket is created, that is any time the Observable returned by the function <code>[sockets](https://gist.github.com/EnricoPicci/35f3c3a2a2a3f96cfdf7b89d46a5d499)</code> emits. Therefore, we need to merge all the events that win the race. We need to use the <code>mergeMap</code> operator, which merges all the events raised by the Observables involved, and flatten the results into a new Observable (<code>mergeMap</code> was formerly know as <code>flatMap</code>).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ieEjio8CpdLJeO8Cje8ezA.png" alt="Image" width="800" height="421" loading="lazy">
<em>Observable that emits specific events depending on the nature of the Client</em></p>
<p>The code to obtain this result is the following:</p>
<pre><code class="lang-js">startSocketServer(httpServer: Server) {
    sockets(httpServer, <span class="hljs-built_in">this</span>.port).pipe(
        mergeMap(<span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span>
            race(
                socket.onMessageType(MessageType.BIND_MONITOR),
                socket.onMessageType(MessageType.BIND_CONTROLLER)
            )
        )
    )
    .subscribe();
}
</code></pre>
<p>Now that we know how to differentiate <strong>Controllers</strong> and <strong>Monitors</strong>, we can focus on what to do in these two cases.</p>
<h3 id="heading-events-relevant-for-a-monitor">Events relevant for a Monitor</h3>
<p>A <strong>Monitor</strong> shows the movement of all <strong>MobileObjects</strong> which are running on the <strong>MobileObjectServer</strong>. So the <strong>MobileObjectServer</strong> has to send the right information to the monitors at the right times. Let’s see first what those times are, that is which are the relevant events that the <strong>MobileObjectServer</strong> has to be aware of in order to fulfill its job.</p>
<h4 id="heading-adding-and-removing-mobileobjects">Adding and removing MobileObjects</h4>
<p>The first relevant events are:</p>
<ul>
<li>a <strong>MobileObject</strong> has been added =&gt; the MobileObject is shown on t<strong>he Moni</strong>tor</li>
<li>a <strong>MobileObject</strong> has been removed =&gt; the MobileObject is removed from t<strong>he Moni</strong>tor</li>
</ul>
<p><strong>MobileObjects</strong> are added or removed over time, so such events can be modeled with two Observables:</p>
<ul>
<li>an Observable which emits when a <strong>MobileObject</strong> is added</li>
<li>an Observable which emits when a <strong>MobileObject</strong> is removed</li>
</ul>
<p>Once a <strong>Monitor</strong> is connected, the <strong>MobileObjectServer</strong> starts being interested in both of those Observables, so it has to <code>merge</code> them:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*DL6Y8XNzv-8TjdV-A5_70A.png" alt="Image" width="800" height="402" loading="lazy">
<em>Merging MobileObject added and removed events for a Monitor</em></p>
<p>Similar to what we have seen before, we need to repeat such logic any time a <strong>Monitor</strong> is added. Therefore we need to <code>mergeMap</code> all the Observables which are the result of the <code>merge</code> of the <em>‘mobile object added’</em> Observable with the <em>‘mobile object removed’</em> Observable.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*T8Pfbzu-eR4JH3PYwmQCFQ.png" alt="Image" width="800" height="399" loading="lazy">
<em>Events for MobileObject added and removed for all Monitors</em></p>
<p>This is the code to obtain an Observable which emits any time a <strong>MobileObject</strong> has to be added to or removed from every <strong>Monitor:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {sockets} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-io-observable'</span>;
<span class="hljs-keyword">import</span> {SocketObs} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-obs'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MobileObjectServer</span> </span>{
    private mobileObjectAdded = <span class="hljs-keyword">new</span> Subject&lt;{<span class="hljs-attr">mobObj</span>: MobileObject, <span class="hljs-attr">mobObjId</span>: string}&gt;();
    private mobileObjectRemoved = <span class="hljs-keyword">new</span> Subject&lt;string&gt;();

    startSocketServer(httpServer: Server) {
        sockets(httpServer, <span class="hljs-built_in">this</span>.port).pipe(
            mergeMap(<span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span>
                race(
                    socket.onMessageType(MessageType.BIND_MONITOR)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(socketObs))
                    ),
                    socket.onMessageType(MessageType.BIND_CONTROLLER)
                    <span class="hljs-comment">// something will be added here soon to make this logic work</span>
                )
                .pipe(
                    mergeMap(<span class="hljs-function"><span class="hljs-params">handler</span> =&gt;</span> handler(socket))
                )
            )
        )
        .subscribe();
    }

    handleMonitorObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> mobObjAdded = <span class="hljs-built_in">this</span>.mobileObjectAdded;
        <span class="hljs-keyword">const</span> mobObjRemoved = <span class="hljs-built_in">this</span>.mobileObjectRemoved;
        <span class="hljs-keyword">return</span> merge(mobObjAdded, mobObjRemoved);
    }
}
</code></pre>
<p>We have introduced a few things with this code which are worth commenting on here.</p>
<p>We have created the <code>MobileObjectServer</code> class, which will be the place where we will code all our server logic from now on.</p>
<p>The method <code>handleMonitorsObs</code>, which we are going to enrich later on, returns simply the <code>merge</code> of two Observables, <code>mobileObjectAdded</code> and <code>mobileObjectRemoved</code>, which are Subjects. This is the “inner” <code>merge</code> shown in the picture above.</p>
<p>Subjects are Observables, and therefore can be merged as we do here. But Subjects are also Observers, so we can emit events through them. As we will see later in the code, there will be a time when we will use these Subjects to emit the events their names suggest.</p>
<p>The last point is related to the code we have added in the startSocketServer method:</p>
<pre><code>race(
   socket.onMessageType(MessageType.BIND_MONITOR)
   .pipe(
      map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">sObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(sObs))
   ),
   socket.onMessageType(MessageType.BIND_CONTROLLER)
   <span class="hljs-comment">// something will be added here soon to make this logic work</span>
)
.pipe(
   mergeMap(<span class="hljs-function"><span class="hljs-params">handler</span> =&gt;</span> handler(socket))
)
</code></pre><p>This is basically a way to say: any time a BIND_MONITOR message is received, return the function</p>
<pre><code class="lang-js">(socketObs: SocketObs) =&gt; <span class="hljs-built_in">this</span>.handleMonitorObs(socketObs)
</code></pre>
<p>which will be executed within the <code>mergeMap</code> operator piped into the result of the <code>race</code> function. This <code>mergeMap</code> operator is the external <code>mergeMap</code> shown in the picture above.</p>
<p>Another way to read the code is the following: any event corresponding to a message of type BIND_MONITOR gets transformed by the logic of</p>
<pre><code>mergeMap(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(socket))
</code></pre><p>where <code>socket</code> is the instance of type <code>SocketsObs</code> emitted by the <code>race</code> function.</p>
<p>Soon we will add something similar for the BIND_CONTROLLER case to make this whole logic work.</p>
<h4 id="heading-handle-mobileobject-dynamics-observables">Handle MobileObject dynamics Observables</h4>
<p>Let’s consider one <strong>Monitor</strong> which connects to the <strong>MobileObjectServer</strong>. After the connection, a couple of MobileObjects are added to the <strong>MobileObjectServer</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YRY2hAFqwOZVkNQ3I32mAw.png" alt="Image" width="611" height="286" loading="lazy">
<em>MobileObjects added for one Monitor</em></p>
<p>Now for each <strong>MobileObject,</strong> we have to start considering the dynamics Observables they offer as part of their APIs. These Observables emit, at regular intervals of time, data about the dynamics (position and velocity) of the <strong>MobileObject</strong>. If <code>mobileObject</code> stores a reference to a <strong>MobileObject</strong>, we can obtain its dynamics Observable via <code>mobileObject.dynamicsObs</code> (see MobileObject APIs).</p>
<p>First we have to transform each event representing the fact that a <strong>MobileObject</strong> has been added into the series of events emitted by its <code>dynamicsObs</code>. Then we <code>mergeMap</code> all these series into a new single Observable which emits all dynamic events for all MobileObjects which are added.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UTxwGbTOjjdLsq9Nh1Il3w.png" alt="Image" width="800" height="581" loading="lazy">
<em>Dynamics events for a single Monitor</em></p>
<p>Then we apply all this jazz to all the <strong>Monitors</strong> which connect to the <strong>MobileObjectServer.</strong> So we end up with a new Observable which emits dynamics data for all <strong>Monitors</strong> and all <strong>MobileObjects</strong> (plus all events related to the fact that a <strong>MobileObject</strong> has been removed).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*r2U2J0j342nGlDEK4-Rwsw.png" alt="Image" width="800" height="439" loading="lazy">
<em>Relevant events for all Monitors</em></p>
<p>Per each time interval, we have groups of four events related to the emission of data about the dynamics of our <strong>MobileObjects</strong>. Why? This makes sense if we think that we have two <strong>Monitors</strong> and two <strong>MobileObjects</strong>. Each <strong>MobileObject</strong> has to send its dynamics data to each <strong>Monitor</strong> per every time interval. Therefore it is correct to see four events per each time interval.</p>
<p>Once this is clear, the code is very simple:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {sockets} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-io-observable'</span>;
<span class="hljs-keyword">import</span> {SocketObs} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-obs'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MobileObjectServer</span> </span>{
    private mobileObjectAdded = <span class="hljs-keyword">new</span> Subject&lt;{<span class="hljs-attr">mobObj</span>: MobileObject, <span class="hljs-attr">mobObjId</span>: string}&gt;();
    private mobileObjectRemoved = <span class="hljs-keyword">new</span> Subject&lt;string&gt;();


    startSocketServer(httpServer: Server) {
        sockets(httpServer, <span class="hljs-built_in">this</span>.port).pipe(
            mergeMap(<span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span>
                race(
                    socket.onMessageType(MessageType.BIND_MONITOR)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(socketObs))
                    ),
                    socket.onMessageType(MessageType.BIND_CONTROLLER)
                    <span class="hljs-comment">// something will be added here soon to make this logic work</span>
                )
                .pipe(
                    mergeMap(<span class="hljs-function"><span class="hljs-params">handler</span> =&gt;</span> handler(socket))
                )
            )
        )
        .subscribe();
    }

    handleMonitorObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> mobObjAdded = <span class="hljs-built_in">this</span>.mobileObjectAdded
                              .pipe(
                                mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> data.mobileObject.dynamicsObs)
                              );
        <span class="hljs-keyword">const</span> mobObjRemoved = <span class="hljs-built_in">this</span>.mobileObjectRemoved;
        <span class="hljs-keyword">return</span> merge(mobObjAdded, mobObjRemoved);
    }

}
</code></pre>
<p>We have just introduced one simple change. We changed the <code>handleMonitorObs</code> method to add the <code>mergeMap</code> operator. This transforms the <code>mobileObjectAdded</code> Observable so that the new Observable emits the dynamics data we are looking for.</p>
<p>The rest has remained untouched.</p>
<h3 id="heading-summary-so-far">Summary so far</h3>
<p>What have we done so far? We have just transformed Observables to obtain new Observables which emit all the events <strong>MobileObjectServer</strong> is interested in when it has to deal with a <strong>Monitor</strong>. Nothing else.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*zDynxsrbo7Vh5U915jKXlA.png" alt="Image" width="800" height="398" loading="lazy">
<em>Transformations of Observables relevant for Monitors</em></p>
<p>You can see how these transformations are reflected in the code in the following image:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*tFariAfbE7FLeRr_1GeCAg.png" alt="Image" width="800" height="422" loading="lazy"></p>
<p>The only thing we need to do now is to add the desired <em>side effects</em> to the relevant events. This will eventually allow us to achieve what we want, that is to communicate to the Monitor the right information at the right time.</p>
<p>But before moving to <em>side effects</em>, let’s cover what <strong>MobileObjectServer</strong> needs to do when interacting with a <strong>Controller</strong>, the other client in our distributed system.</p>
<h3 id="heading-events-relevant-for-a-controller">Events relevant for a Controller</h3>
<p>When a <strong>Controller</strong> connects to the <strong>MobileObjectServer</strong> there are fewer things that the server needs to care about. At least there are fewer nested relevant events happening.</p>
<p>The things that the <strong>MobileObjectServer</strong> needs to care about are:</p>
<ul>
<li>A <strong>Controller</strong> has connected, which in our simple logic means that we have to create a brand new <strong>MobileObject</strong></li>
<li>The <strong>Controller</strong> has sent commands for its <strong>MobileObject</strong></li>
<li>The <strong>Controller</strong> has disconnected. In our implementation, this means that we somehow have to delete the <strong>MobileObject</strong> controlled by the <strong>Controller</strong> (we have a 1 to 1 relationship between <strong>MobileObject</strong> and its <strong>Controller</strong>)</li>
</ul>
<p>We already know the first event: it is the one emitted by the Observable returned by <code>socket.onMessageType(BIND_CONTROLLER)</code>.</p>
<p>Commands are sent by the <strong>Controller</strong> to the <strong>MobileObjectServer</strong> in the form of messages. So we can create an Observable of commands received over a certain _socket (_received from a certain Controller) since each Controller has its own <em>socket.</em> We do this by simply using the <code>onMessageType</code> method of <code>SocketObs</code></p>
<pre><code>socket.onMessageType(CONTROLLER_COMMAND)
</code></pre><p><code>SocketObs</code> also offers a method, <code>onDisconnect</code>, which returns an Observable that emits when the <em>socket</em> is disconnected. This is what we need in order to deal with the third event.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*LFWTYTT9W7p0gcNK3GrqoA.png" alt="Image" width="800" height="398" loading="lazy">
<em>Events relevant when a Controller connects to MobileObjectServer</em></p>
<p>Since we are dealing with more than one <strong>Controller</strong> potentially connecting to the <strong>MobileObjectServer</strong>, it should not surprise you to learn that we need to <code>mergeMap</code> the result of the <code>merge</code>. This is the same type of transformation we have already done a few times.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UoOipJVQ4KsaEpVlF5VRDA.png" alt="Image" width="800" height="491" loading="lazy"></p>
<p>The code should be no surprise as well.</p>
<pre><code class="lang-js">startSocketServer(httpServer: Server) {
        sockets(httpServer, <span class="hljs-built_in">this</span>.port).pipe(
            mergeMap(<span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span>
                race(
                    socket.onMessageType(MessageType.BIND_MONITOR)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(socketObs))
                    ),
                    socket.onMessageType(MessageType.BIND_CONTROLLER)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleControllerObs(socketObs))
                    ),
                )
                .pipe(
                    mergeMap(<span class="hljs-function"><span class="hljs-params">handler</span> =&gt;</span> handler(socket))
                )
            )
        )
        .subscribe();
}

handleMonitorObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> mobObjAdded = <span class="hljs-built_in">this</span>.mobileObjectAdded
                              .pipe(
                                mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> data.mobileObject.dynamicsObs)
                              );
        <span class="hljs-keyword">const</span> mobObjRemoved = <span class="hljs-built_in">this</span>.mobileObjectRemoved;
        <span class="hljs-keyword">return</span> merge(mobObjAdded, mobObjRemoved);
}

handleControllerObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> commands = socket.onMessageType(MessageType.CONTROLLER_COMMAND);
        <span class="hljs-keyword">const</span> disconnect = socket.onDisconnect();

        <span class="hljs-keyword">return</span> merge(commands, disconnect);
}
</code></pre>
<p>We have simply added an <code>handleControllerObs</code> method that deals with <em>commands received</em> and the <em>disconnect</em> of a Controller. We apply the mergeMap transformation to it as we have already done with <code>handleMonitorObs</code>.</p>
<h4 id="heading-summary-of-the-transformations-applied-to-controllers"><strong>Summary of the transformations applied to Controllers</strong></h4>
<p>The following diagram illustrates all transformations we have applied starting from the Observable that emits when a <strong>Controller</strong> connects.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UoOipJVQ4KsaEpVlF5VRDA.png" alt="Image" width="800" height="491" loading="lazy">
<em>Transformations of event streams (Observables) relevant for Controllers</em></p>
<h3 id="heading-the-final-observable">The Final Observable</h3>
<p>If we put together the transformations we have done for both the <strong>Monitors</strong> and the <strong>Controllers,</strong> what we obtain is the following final Observable.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*vrRAT7gGmSBn2QsR7XmyIQ.png" alt="Image" width="800" height="607" loading="lazy">
<em>The tree of events produced subscribing the Final Observable</em></p>
<p>Just by subscribing to this one final Observable, the whole tree of events gets unfolded.</p>
<h3 id="heading-side-effects">Side effects</h3>
<p>The beautiful tree of events we have created by subscribing to the Final Observable does not do anything. But it does a good job of mapping the <strong><em>Events</em></strong> we identified while describing the requirements of the Server at the beginning of this article.</p>
<p>Basically it tells us clearly when we have to do <em>something</em>.</p>
<p>This <em>something</em> is what we call a <em>side effect</em>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*jTYJFA6ScG_uakdASIRIRA.png" alt="Image" width="800" height="574" loading="lazy">
<em>Side effects</em></p>
<p>When a Controller connects and disconnects, we respectively create or delete a <strong>MobileObject</strong>. As <em>side effect</em> of these actions is that we raise “<em>MobileObject added”</em> and <em>“MobileObject deleted”</em> events using the <code>mobileObjectAdded</code> and <code>mobileObjectRemoved</code> Subjects we introduces some paragraphs ago.</p>
<h4 id="heading-how-to-implement-side-effects">How to implement <em>side effects</em></h4>
<p>In RxJs there are different ways to implement <em>side effects</em>.</p>
<p>Observers is one. We can add Observers while we <code>subscribe</code> using the <code>tap</code> operator (formerly know as <code>do</code>).</p>
<p>Another way is to inject them in any function we pass to any RxJs operator.</p>
<p>We are mainly going to use <code>tap</code>, since it allows us to place side effects throughout the entire tree of events. But we are also going to place side effects directly inside functions we pass to RxJs operators.</p>
<p>The only place we do not put side effects is <code>subscribe</code>. The reason is that, given how we built it, the Final Observer emits many different types of events. Therefore <code>subscribe</code>, which works the same for all events, is not the right place to put behavior which depends on certain types of events.</p>
<p>Hopefully at this point the code sort of speaks for itself.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*x4BfIT5unvy9VT2u8NEUYQ.png" alt="Image" width="800" height="574" loading="lazy">
<em>Implementation of Side Effects in the code</em></p>
<h3 id="heading-last-but-not-least-completion-of-observables">Last but not least: completion of Observables</h3>
<p>There is one thing that we still need to do to complete our design: stop the streams of events, or complete the Observables, when either a <strong>Controller</strong> or a <strong>Monitor</strong> disconnects.</p>
<h4 id="heading-when-a-controller-disconnects">When a Controller disconnects</h4>
<p>When a Controller disconnects, we delete the <strong>MobileObject</strong> it controls. As part of the deletion, it is important to make sure that the <strong>MobileObjectServer</strong> stops sending dynamics data related to this <strong>MobileObject</strong> to the connected Monitors. This means that we must complete the following Observable:</p>
<pre><code class="lang-js">mobObjInfo.mobObj.dynamicsObs
.pipe(
  tap(<span class="hljs-function"><span class="hljs-params">dynamics</span> =&gt;</span> socket.send(MessageType.DYNAMICS_INFO, dynamics)),
)
</code></pre>
<p>We can easily achieve this just using the <code>takeUntil</code> operator together with the <code>mobileObjectRemoved</code> Observable we already know:</p>
<pre><code class="lang-js">mobObjInfo.mobObj.dynamicsObs
.pipe(
  tap(<span class="hljs-function"><span class="hljs-params">dynamics</span> =&gt;</span> socket.send(MessageType.DYNAMICS_INFO, dynamics)),
  takeUntil(<span class="hljs-built_in">this</span>.mobileObjectRemoved.pipe(
    filter(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> id === mobObjInfo.mobObjId)
  ))
)
</code></pre>
<p><code>takeUntil</code> ensures that an Observable completes when the Observable passed as a parameter to <code>takeUntil</code> emits.</p>
<p><code>mobileObjectRemoved</code> emits every time a <strong>MobileObject</strong> is removed. What we want, though, is to stop sending dynamics info when a specific <strong>MobileObject</strong>, identified by its id, is removed. So we add the <code>filter</code> logic.</p>
<h4 id="heading-when-a-monitor-disconnects">When a Monitor disconnects</h4>
<p>In this case, we can also use <strong>takeUntil</strong>.</p>
<p>We know when a Monitor disconnects because the <code>socket</code>, of type <code>SocketObs</code>, associated to it emits via the <code>socket.onDisconnect()</code> Observable. So what we need to do is stop sending dynamics info when <code>socket.onDisconnect()</code> emits.</p>
<p>So the final logic to govern the completion of the Observable is</p>
<pre><code class="lang-js">mobObjInfo.mobObj.dynamicsObs
.pipe(
  tap(<span class="hljs-function"><span class="hljs-params">dynamics</span> =&gt;</span> socket.send(MessageType.DYNAMICS_INFO, dynamics)),
  takeUntil(<span class="hljs-built_in">this</span>.stopSendDynamics(socket, mobObjInfo.mobObjId))
)
</code></pre>
<p>where</p>
<pre><code>private stopSendDynamics(socket: SocketObs, <span class="hljs-attr">mobObjId</span>: string){
  <span class="hljs-keyword">return</span> merge(
            <span class="hljs-built_in">this</span>.mobileObjectRemoved.pipe(
                                       filter(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> id === mobObjId)
                                     ),
            socket.onDisconnect()
  );
}
</code></pre><p>And this is how the core of the code implementing our logic looks:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {sockets} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-io-observable'</span>;
<span class="hljs-keyword">import</span> {SocketObs} <span class="hljs-keyword">from</span> <span class="hljs-string">'./socket-obs'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MobileObjectServer</span> </span>{
    private mobileObjectAdded = <span class="hljs-keyword">new</span> Subject&lt;{<span class="hljs-attr">mobObj</span>: MobileObject, <span class="hljs-attr">mobObjId</span>: string}&gt;();
    private mobileObjectRemoved = <span class="hljs-keyword">new</span> Subject&lt;string&gt;();


        public startSocketServer(httpServer: Server) {
        sockets(httpServer, <span class="hljs-built_in">this</span>.port).pipe(
            mergeMap(<span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span>
                race(
                    socket.onMessageType(MessageType.BIND_MONITOR)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleMonitorObs(socketObs))
                    ),
                    socket.onMessageType(MessageType.BIND_CONTROLLER)
                    .pipe(
                        map(<span class="hljs-function">() =&gt;</span> <span class="hljs-function">(<span class="hljs-params">socketObs: SocketObs</span>) =&gt;</span> <span class="hljs-built_in">this</span>.handleControllerObs(socketObs))
                    ),
                )
                .pipe(
                    mergeMap(<span class="hljs-function"><span class="hljs-params">handler</span> =&gt;</span> handler(socket)) 
                )
            )
        )
        .subscribe();
    }


    private handleMonitorObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> mobObjAdded = <span class="hljs-built_in">this</span>.mobileObjectAdded
                                .pipe(
                                    tap(<span class="hljs-function"><span class="hljs-params">mobObjInfo</span> =&gt;</span> socket.send(MessageType.MOBILE_OBJECT, mobObjInfo.mobObjId)),
                                    mergeMap(<span class="hljs-function"><span class="hljs-params">mobObjInfo</span> =&gt;</span> mobObjInfo.mobObj.dynamicsObs
                                                    .pipe(
                                                        tap(<span class="hljs-function"><span class="hljs-params">dynamics</span> =&gt;</span> socket.send(MessageType.DYNAMICS_INFO, dynamics)),
                                                        takeUntil(<span class="hljs-built_in">this</span>.stopSendDynamicsInfo(socket, mobObjInfo.mobObjId))
                                                    )
                                    )
                                );
        <span class="hljs-keyword">const</span> mobObjRemoved = <span class="hljs-built_in">this</span>.mobileObjectRemoved
                                .pipe(
                                    tap(<span class="hljs-function"><span class="hljs-params">mobObjId</span> =&gt;</span> socket.send(MessageType.MOBILE_OBJECT_REMOVED, mobObjId)),
                                );
        <span class="hljs-keyword">return</span> merge(mobObjAdded, mobObjRemoved);
    }

    private handleControllerObs(socket: SocketObs) {
        <span class="hljs-keyword">const</span> {mobObj, mobObjId} = <span class="hljs-built_in">this</span>.newMobileObject();

        <span class="hljs-built_in">this</span>.mobileObjectAdded.next({mobObj, mobObjId});

        <span class="hljs-keyword">const</span> commands = socket.onMessageType(MessageType.CONTROLLER_COMMAND)
                        .pipe(
                            tap(<span class="hljs-function"><span class="hljs-params">command</span>  =&gt;</span> <span class="hljs-built_in">this</span>.execute(command, mobObj))
                        );

        <span class="hljs-keyword">const</span> disconnect = socket.onDisconnect()
                        .pipe(
                            tap(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.mobileObjectRemoved.next(mobObjId)),
                        );

        <span class="hljs-keyword">return</span> merge(commands, disconnect);
    }

    private stopSendDynamicsInfo(socket: SocketObs, <span class="hljs-attr">mobObjId</span>: string) {
        <span class="hljs-keyword">return</span> merge(<span class="hljs-built_in">this</span>.mobileObjectRemoved.pipe(filter(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> id === mobObjId)), socket.onDisconnect());
    }

}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>It has been a pretty long journey. We have seen some reasoning driven by Reactive Thinking and some implementations of this reasoning.</p>
<p>We started transforming WebSockets events into Observables. Then, applying incremental transformations, we ended up creating a single Observable that, once subscribed, unfolds all the events we are interested in.</p>
<p>At this point, adding the side effects that allow us to achieve our goal has been straightforward.</p>
<p>This mental process of design, which is incremental in itself, is the meaning I give to “Reactive Thinking”.</p>
<p>The full code base, comprising Server Controller and Monitor, can be found <a target="_blank" href="https://github.com/EnricoPicci/mobile-object-observables">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Reactive programming and Observable sequences with RxJS in Node.js ]]>
                </title>
                <description>
                    <![CDATA[ By Enrico Piccinin Dealing with asynchronous non-blocking processing has always been the norm in the JavaScript world, and now is becoming very popular in many other contexts. The benefits are clear: an efficient use of resources. But the benefits co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rxjs-and-node-8f4e0acebc7c/</link>
                <guid isPermaLink="false">66d4608ec7632f8bfbf1e47b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 23 Dec 2017 11:16:07 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*gpmVC7PYhD3ZYHBYltyeXw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Enrico Piccinin</p>
<p>Dealing with asynchronous non-blocking processing has always been the norm in the JavaScript world, and now is becoming very popular in many other contexts. The benefits are clear: an efficient use of resources. But the benefits come at a cost: a non-trivial increase in complexity.</p>
<p>Over time, vendors and the open source community have tried to find ways to reduce such complexity without compromising the benefits.</p>
<p>Asynchronous processing started with ‘callbacks’, then came Promise and Future, async and await. Recently another kid has come to town — <a target="_blank" href="http://reactivex.io/">ReactiveX</a> with its various language implementations — bringing the developers a new powerful tool, the Observable.</p>
<p>In this article, we want to show how Observables implemented by <a target="_blank" href="http://reactivex.io/rxjs/">RxJs</a> (the JavaScript embodiment of ReactiveX) can simplify code to be executed with Node.js, the popular server-side JavaScript non-blocking environment.</p>
<h3 id="heading-a-simple-use-case-read-transform-write-and-log">A simple use case — Read, Transform, Write, and Log</h3>
<p>To make our reasoning concrete, let’s start from a simple use case. Let’s assume we need to read the files contained in <code>**Source Dir**</code>, transform their content and write the new transformed files in a <code>**Target Dir**</code><em>,</em> while keeping a log of the files we have created.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/t6BDM5ShfozMhO6juTt2pT5hoxj6C-XnQe8G" alt="Image" width="800" height="361" loading="lazy">
<em>Read — Transform — Write — Log</em></p>
<h3 id="heading-synchronous-implementation">Synchronous implementation</h3>
<p>The synchronous implementation of this use case is pretty straightforward. In a sort of pseudo code representation, we could think of something like:</p>
<pre><code>read the names <span class="hljs-keyword">of</span> the files <span class="hljs-keyword">of</span> Source Dir
   <span class="hljs-keyword">for</span> each file name
      read the file
      transform the content
      write the <span class="hljs-keyword">new</span> file <span class="hljs-keyword">in</span> Target Dir
      log the name <span class="hljs-keyword">of</span> the <span class="hljs-keyword">new</span> file
   end <span class="hljs-keyword">for</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am done'</span>)
</code></pre><p>There is nothing special to comment here. We can just say that we are sure of the sequence of execution of each line and that we are sure that things will happen as described by the following flow of events. Each circle corresponds to the completion of an I/O operation.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VkuJvfZCN7Ps5vLDx4OvCxcU1pfo3MsHYkGc" alt="Image" width="800" height="86" loading="lazy">
<em>The sequence of events in a synchronous world</em></p>
<h3 id="heading-what-happens-in-an-asynchronous-non-blocking-environment-like-nodejs">What happens in an asynchronous non-blocking environment like Node.js</h3>
<p>Node.js is an asynchronous non-blocking execution environment for JavaScript. Non-blocking means that Node.js does not wait for I/O or Network operations to complete before moving to the execution of the next line of code.</p>
<h4 id="heading-processing-one-file"><strong>Processing one file</strong></h4>
<p>Reading and writing files are I/O operations where Node.js shows its non-blocking nature. If a Node.js program asks for a file to read, it has to provide a function to be executed when the file content is available (the so called <strong>callback</strong>) and then immediately move on to the next operation to execute.</p>
<p>Let’s consider the case of just <strong>one file</strong>. Reading, transforming, writing <strong>one</strong> file and updating the log in Node.js looks something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>; <span class="hljs-comment">// Node module to access file system</span>
<span class="hljs-keyword">const</span> fileName = <span class="hljs-string">'one-file.txt'</span>;
fs.readFile(fileName, callback(err, data) =&gt; {
   <span class="hljs-keyword">const</span> newContent = transform(data);
   <span class="hljs-keyword">const</span> newFileName = newFileName(fileName); <span class="hljs-comment">// calculate new name</span>
   fs.writeFile(newFileName, newContent, <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
      <span class="hljs-keyword">if</span>(err) {<span class="hljs-comment">// handle error};</span>
      fs.appendFile(<span class="hljs-string">'log.txt'</span>, newFileName  + <span class="hljs-string">' written'</span>, err = {
         <span class="hljs-keyword">if</span> (err) {<span class="hljs-comment">// handle error}</span>
      });
   });
})
</code></pre>
<p>The syntax may look a bit convoluted with 2 levels of indentation, but if we think of what happens in terms of events we can still precisely foresee the sequence:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CZESn-CUe78yiDYRe0a79MZH81ZZuAu7mBrJ" alt="Image" width="800" height="87" loading="lazy">
<em>Sequence of events in Node while transforming 1 file</em></p>
<h4 id="heading-the-paradise-of-promise"><strong>The paradise of Promise</strong></h4>
<p>This is the use case where JavaScript Promise shines. Using Promise we can make the code look again sequential, without interfering with the asynchronous nature of Node.js.</p>
<p>Assuming we can access functions that perform read and write operations on file and return a Promise, then our code would look like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fileName = <span class="hljs-string">'my-file.txt'</span>;
readFilePromise(fileName)
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
   <span class="hljs-keyword">const</span> newContent = transform(data);
   <span class="hljs-keyword">const</span> newFileName = newFileName(fileName); <span class="hljs-comment">// build the new name</span>
   <span class="hljs-keyword">return</span> writeFilePromise(newFileName, newContent)
})
.then(<span class="hljs-function"><span class="hljs-params">newFileName</span> =&gt;</span> appendFile(<span class="hljs-string">'log.txt'</span>, newFileName))
.then(<span class="hljs-function"><span class="hljs-params">newFileName</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(newFileName + <span class="hljs-string">' written'</span>))
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-comment">// handle error)</span>
</code></pre>
<p>There are several ways to transform Node.js functions in <code>Promise</code> based functions. This is one example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readFilePromise</span>(<span class="hljs-params">fileName: string</span>): <span class="hljs-title">Promise</span>&lt;<span class="hljs-title">Buffer</span>&gt;</span>{
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
      fs.readFile(fileName, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data: Buffer</span>) </span>{
         <span class="hljs-keyword">if</span>(err !== <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> reject(err);
         resolve(data);
      });
   });
}
</code></pre>
<h4 id="heading-processing-many-files"><strong>Processing many files</strong></h4>
<p>If we return to the original use case, where we have to transform all the files contained in a Directory, the complexity increases and Promises start showing some limits.</p>
<p>Let’s look at the events the Node.js implementation needs to manage:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PRMavRZ7dF0oaWIHXqkCq6-e0Xfm0HR5m1-u" alt="Image" width="800" height="253" loading="lazy">
<em>Sequence of events when transforming many files in parallel</em></p>
<p>Each circle represents the completion of one I/O operation, either read or write. Every line represents the processing of one specific file, or a chain of Promises.</p>
<p>Given the non-blocking nature of Node.js, there is no certainty on the sequence in time of such events. It is possible that we will finish writing <code>**File2**</code> before we finish reading <code>**File3**</code>.</p>
<p>The parallel processing of each file makes the use of Promises more complex (at the end of this article, a Promise based implementation is provided). This is the scenario where ReactiveX — RxJs in particular — and Observable shine and allow you to build elegant solutions.</p>
<h3 id="heading-what-are-observables-and-what-can-you-do-with-them">What are Observables and what can you do with them?</h3>
<p>There are many places where formal definitions of Observables are detailed, starting from the official site of <a target="_blank" href="http://reactivex.io/intro.html">ReactiveX</a>.</p>
<p>Here I just want to remind you of a couple of properties that have always gotten my attention:</p>
<ul>
<li>Observable models a <strong>stream of events</strong></li>
<li>Observable is the <strong>“push”</strong> brother of Iterable, which is “pull”</li>
</ul>
<p>As the “push” brother of Iterable, Observable offers developers many of the cool features provided by Iterables such as:</p>
<ul>
<li>Transform “streams of events” or Observables, via operators such as <code>map</code>, <code>filter</code>and <code>skip</code></li>
<li>Apply functional programming style</li>
</ul>
<p>One additional very important thing that Observable offers is subscription. Via subscription, the code can apply “side effects” to events and perform specific actions when specific events happen, such as when errors occur or the stream of events completes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZXgqj1SdhavRZdcReV9aBvtTnLZ3r8jODhNz" alt="Image" width="800" height="389" loading="lazy">
<em>The subscribe interface of Observable</em></p>
<p>As you can see, the Observable interface gives developers the possibility to provide three different functions which define what to do respectively when: an event is emitted with its data, an error occurs, or the stream of events completes.</p>
<p>I guess all of the above may sound very theoretical to those who have not yet played with Observable, but hopefully the next part of the discussion, which is focused on our use case, will make these concepts more concrete.</p>
<h3 id="heading-implementation-of-the-read-transform-write-and-log-use-case-via-observable">Implementation of the Read, Transform, Write, and Log use case via Observable</h3>
<p>Our use case starts with reading the list of files contained in <code>**Source Dir**</code>. So, let’s start from there.</p>
<h4 id="heading-read-all-the-file-names-contained-in-a-directory"><strong>Read all the file names contained in a Directory</strong></h4>
<p>Let’s assume we have access to a function which receives as input the name of a directory and returns an Observable which emits the list of file names of the directory once the directory tree structure has been read.</p>
<pre><code>readDirObservable(dirName: string) : Observable&lt;<span class="hljs-built_in">Array</span>&lt;string&gt;&gt;
</code></pre><p>We can subscribe to this Observable and when all file names have been read, start doing something with them:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BeSolRYnvm1Cj0rhkQtZXbtqkopSZ-yCELo8" alt="Image" width="800" height="192" loading="lazy">
<em>Subscription to an Observable which emits when the directory has been read</em></p>
<h4 id="heading-read-a-list-of-files"><strong>Read a list of files</strong></h4>
<p>Let’s assume now that we can access a function which receives as input a list of file names and emits each time a file has been read (it emits the content of the file <code>Buffer</code>, and its name <code>string</code>).</p>
<pre><code>readFilesObservable(fileList: <span class="hljs-built_in">Array</span>&lt;string&gt;) 
   : Observable&lt;{<span class="hljs-attr">content</span>: Buffer, <span class="hljs-attr">fileName</span>: string}&gt;
</code></pre><p>We can subscribe to such <code>Observable</code> and start doing something with the content of the files.</p>
<h4 id="heading-combining-observables-switchmap-operator">Combining Observables — <em>switchMap</em> operator</h4>
<p>We have now two Observables, one that emits a list of file names when the directory has been read and one that emits every time a file is read.</p>
<p>We need to combine them to implement the first step of our use case, which is: when <code>readDirObservable</code> emits, we need to <strong>switch</strong> to <code>readFilesObservable</code> .</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iWmO0g9KdUw64scmcB5OGgbsOJarDfwyIGZg" alt="Image" width="800" height="165" loading="lazy">
<em>switchMap operator</em></p>
<p>The trick here is performed by the <code>switchMap</code> operator. The code looks like:</p>
<pre><code>readDirObservable(dirName)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data.fileName + ‘ read’), <span class="hljs-comment">// do stuff with the data received</span>
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files read’)
)
</code></pre><p>We must mention that the <code>switchMap</code> operator is more powerful than this. Its full power though can not be appreciated in this simple use case, and its full description is outside the scope of this post. If you are interested, this is an <a target="_blank" href="https://blog.angular-university.io/rxjs-switchmap-operator/">excellent article</a> that describes in detail <code>switchMap</code>.</p>
<h4 id="heading-observable-generating-a-stream-of-observables"><strong>Observable generating a stream of Observables</strong></h4>
<p>We have now a stream of events representing the completion of a <code>read</code> operation. After the <code>read</code> we need to do a transformation of the content that, for sake of simplicity, we assume to be synchronous, and then we need to save the transformed content in a new file.</p>
<p>But writing a new file is again an I/O operation, or a non-blocking operation. So every ‘file-read-completion’ event starts a new path of elaboration that receives as input the content and the name of the source file, and emits when the new file is written in the <code>Target Dir</code> (the event emitted carries the name of the file written).</p>
<p>Again, we assume that we’re able to access a function that emits as soon as the write operation is completed, and the data emitted is the name of the file written.</p>
<pre><code>writeFileObservable(fileName: string, <span class="hljs-attr">content</span>: Buffer) :            Observable&lt;string&gt;
</code></pre><p>In this case, we have different “write-file” Observables, returned by the <code>writeFileObservable</code> function, which emits independently. It would be nice to <strong>merge</strong> them into a new Observable which emits any time each of these “write-file” Observables emit.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/uNh9nBU32X6SbsDi-SAmYy90FhR4we4XLcXv" alt="Image" width="800" height="374" loading="lazy">
<em>A stream of Observables we would like to merge</em></p>
<p>With ReactiveX (or RxJs in JavaScript) we can reach this result using the <code>mergeMap</code> operator (also known as a <strong>flatMap</strong>). This is what the code looks like:</p>
<pre><code>readDirObservable(dir)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> transform(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> writeFileObservable(data.fileName, data.content))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data.fileName + ‘ written’),
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files written’)
)
</code></pre><p>The <code>mergeMap</code> operator has created a new Observable, the <code>writeFileObservable</code> as illustrated in the following diagram:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/reYH02KG9yTsgGuI7cTiPFMCTURzBsFRC07D" alt="Image" width="800" height="260" loading="lazy">
<em>Observable returned by mergeMap operator</em></p>
<h4 id="heading-so-what">So what?</h4>
<p>Applying the same approach, if we just imagine that we have a new function of <code>writeLogObservable</code>, that writes a line on the log as soon as the file is written and emits the file name as soon as the log is updated, the final code for our use case would look like:</p>
<pre><code>readDirObservable(dir)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> transform(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> writeFileObservable(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">fileName</span> =&gt;</span> writeLogObservable(fileName))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(fileName + ‘ logged’),
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files have been transformed’)
)
</code></pre><p>We do not have indentations introduced by the callbacks.</p>
<p>Time flows along the vertical axis only, so we can read the code line by line and reason about what is happening line after line.</p>
<p>We have adopted a functional style.</p>
<p>In other words, we have seen the benefits of Observable in action.</p>
<h3 id="heading-create-observable-from-functions-with-callbacks">Create Observable from functions with callbacks</h3>
<p>I hope you now think that this looks pretty cool. But even in this case you may have one question. All the functions that make this code cool just do not exist. There is no <code>readFilesObservable</code> or <code>writeFileObservable</code> in standard Node.js libraries. How can we create them?</p>
<h4 id="heading-bindcallback-and-bindnodecallback"><strong>bindCallback and bindNodeCallback</strong></h4>
<p>A couple of functions provided by Observable, namely <code>bindCallback</code>(and <code>bindNodeCallback</code>) come to our rescue.</p>
<p>The core idea behind them is to provide a mechanism to transform a function <code>f</code> which accepts a callback <code>cB(cBInput)</code> as input parameter into a function which returns an Observable <code>obsBound</code> which emits <code>cBInput</code>. In other words, it transforms the <strong>invocation</strong> of the <code>cB</code> in the <strong>emission</strong> of <code>cBInput</code>.</p>
<p>The subscriber of <code>obsBound</code> can define the function which will process <code>cBInput</code> (which plays the same role as <code>cB(cBInput)</code>). The convention applied is that the callback function <code>cB(cBInput)</code> must be the last argument of<code>f</code>.</p>
<p>It is probably easier to understand the mechanism looking at the following diagram:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SfAvPHIPSPJmnk3VLeW6ioBOCITEpiebo-Bf" alt="Image" width="800" height="378" loading="lazy">
<em>From a function to an Observable</em></p>
<p>The starting point, the function <strong>f(x, cb)</strong> is the same in the two cases. The result (what is printed on the console) is the same in the two cases.</p>
<p>What is different is how the result is obtained. In the first case the result is determined by the callback function passed as input. In the second case it is determined by the function defined by the subscriber.</p>
<p>Another way of considering how <code>bindCallback</code> works is to look at the transformation it performs, as illustrated in the diagram below.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/MJ-tn3TsJhIDDEPt6ymYxBxgMJ1GYyqNQfHA" alt="Image" width="800" height="134" loading="lazy">
<em>Transformation performed by bindCallback</em></p>
<p>The first argument of <code>f</code> becomes the value passed to the new function <code>fBound</code>. The arguments used as parameters of the callback <code>cb</code> become the values emitted by the new Observable returned by <code>fBound</code>.</p>
<p><code>bindNodeCallback</code> is a variation of <code>bindCallback</code> based on the convention that the callback function has an <strong>error</strong> parameter as the first parameter, along with the Node.js convention <code>fs.readFile(err, cb)</code>.</p>
<h4 id="heading-create-observables-from-non-callback-functions"><strong>Create Observables from non-callback functions</strong></h4>
<p><code>bindNodeCallback</code> has been designed to work with functions which expect a callback as the last argument of their input, but we can make it work also with other functions.</p>
<p>Let’s consider the standard Node.js function <code>readLine</code>. This is a function used to read files line by line. The following example shows as it works:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/41zopDeXW8stNTeBo2BmXMswEucES7U4WASG" alt="Image" width="800" height="166" loading="lazy">
<em>readLine function</em></p>
<p>Each line read is pushed into the <code>lines</code> array. When the file is completely read, the function <code>processLinesCb</code> is called.</p>
<p>Imagine now that we define a new function,<code>_readLines</code>, which wraps the logic defined above as shown by the following snippet:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/2SxYnanPtydSbSaJmkEGmxsWSHU7QIAToPpu" alt="Image" width="800" height="138" loading="lazy">
<em>readLine function wrapped by a callback function</em></p>
<p>Once all lines are read, they are processed by the function <code>processLinesCb</code>, which is the last input parameter of <code>_readLines</code>. <code>_readLines</code> is therefore a function that can be treated by <code>bindCallback</code>. Through this trick we can transform the Node.js function <code>fs.readLine</code> into an Observable using the usual <code>bindCallback</code> function as follows:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FMEHXXKXwbucYZ4s1sVj9OkuavNPUMw972va" alt="Image" width="800" height="69" loading="lazy">
<em>readLine as Observable</em></p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Asynchronous non-blocking processing is complex by nature. Our minds are used to think sequentially — this is true at least for those of us who started coding few years ago. We often find it challenging to reason about what is really happening in these environments. The callback-hell is just around the corner.</p>
<p>Promises and Futures have simplified some of the most frequent cases such as ‘one time’ asynchronous events, the ‘request now — respond later’ scenario typical of HTTP requests.</p>
<p>If we move from ‘one time’ events to ‘event streams’ Promises start showing some limitations. In such cases we may find ReactiveX and Observables a very powerful tool.</p>
<h4 id="heading-as-promised-the-promise-based-implementation-of-our-use-case"><strong>As promised: the Promise-based implementation of our use case</strong></h4>
<p>This is an implementation of the same use case based on Promises:</p>
<pre><code><span class="hljs-keyword">const</span> promises = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">Promise</span>&gt;();
readDirPromise(dir)
.then(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> {
   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> file <span class="hljs-keyword">of</span> fileList) {promises.push(
         readFilePromise(file)
         .then(<span class="hljs-function"><span class="hljs-params">file_content</span> =&gt;</span> transform(file_content))
         .then(<span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> writeLogPromise(file))
      );
   }
   <span class="hljs-keyword">return</span> promises;
}
.then(<span class="hljs-function"><span class="hljs-params">promises</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.all(promises))
.then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘I am done’))
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error })</span>
</code></pre> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
