<?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[ observables - 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[ observables - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 19 May 2026 10:29:32 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/observables/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <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[ 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>
        
    </channel>
</rss>
