<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rachit Saxena on Medium]]></title>
        <description><![CDATA[Stories by Rachit Saxena on Medium]]></description>
        <link>https://medium.com/@rachitsaxenakush1?source=rss-192ec33fd8db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DCUazo9jHPUWTueF</url>
            <title>Stories by Rachit Saxena on Medium</title>
            <link>https://medium.com/@rachitsaxenakush1?source=rss-192ec33fd8db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:23:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rachitsaxenakush1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 Underrated RxJS Operators That Will Supercharge Your Angular Code.]]></title>
            <link>https://medium.com/@rachitsaxenakush1/10-underrated-rxjs-operators-that-will-supercharge-your-angular-code-909586e694d1?source=rss-192ec33fd8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/909586e694d1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[top-10]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Rachit Saxena]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 10:57:22 GMT</pubDate>
            <atom:updated>2025-06-22T11:00:59.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5OyvZiq20MadCyhmmZ01g.png" /></figure><p>You probably use map, filter, and switchMap every day in RxJS—but did you know you can make your streams <strong>compete for the fastest result</strong> with race() <a href="https://rxjs.dev/api/operators/race">RxJS </a>or <strong>prevent ghost clicks and double‑submits</strong> effortlessly using exhaustMap() <a href="https://rxjs.dev/api/operators/exhaustMap">RxJS</a>?<br> These powerful operators are <strong>incredibly simple to integrate</strong> yet <strong>surprisingly underused</strong>—unlocking them can transform your Angular code with minimal effort.</p><blockquote>We are going to discuss about these 10 operators.<br>“materialize &amp; de<em>materialize</em>, subscribeOn, observeOn, groupBy, distinctUntilChanged, distinctUntilKeyChanged, onErrorResultNext, <em>takeUntil</em>, exhaustMap, race”<br>which can defentaly boost your app’s performance and are best practices.</blockquote><blockquote>1.Materialize</blockquote><p>materialize() transforms every emission, error, and completion into concrete Notification objects—turning control signals into streamable data. It doesn&#39;t just observe the stream, it serializes its behavior.</p><pre>import { of, throwError, concat } from &#39;rxjs&#39;;<br>import { materialize } from &#39;rxjs/operators&#39;;<br><br>const source$ = concat(<br>  of(&#39;A&#39;, &#39;B&#39;),<br>  throwError(() =&gt; new Error(&#39;Something went wrong!&#39;))<br>);<br><br>source$.pipe(<br>  materialize()<br>).subscribe(notification =&gt; console.log(notification));<br><br>////////////////////// OUTPUT /////////////////////<br><br>Notification { kind: &#39;N&#39;, value: &#39;A&#39; }  // &#39;Next&#39; value<br>Notification { kind: &#39;N&#39;, value: &#39;B&#39; }<br>Notification { kind: &#39;E&#39;, error: Error(&#39;Something went wrong!&#39;) } // &#39;Error&#39; as value</pre><p><strong>But the Question Arrises :</strong><br>“That can’t we already handle next, error, and complete using subscribe()? Isn’t that enough? If you’re thinking that — you’re not alone.&quot;</p><p><strong>Answer:</strong><br>You’re right — subscribe() lets you <strong>respond</strong> to emissions.<br> But materialize() takes it a step further: it <strong>transforms</strong> every next, error, and complete into actual <strong>data</strong> — Notification objects — that <strong>flow through your stream like regular values</strong>.</p><p>Here’s what that unlocks:</p><ul><li><strong>Turn control signals into streamable data</strong>: next, error, and complete are no longer just callbacks — they become values you can filter, map, or buffer.</li><li><strong>Prevent stream termination on error</strong>: Instead of killing the stream, errors become just another piece of data — perfect for retries, logging, or soft failure handling.</li><li><strong>Audit and debug full stream behavior</strong>: Gain complete insight into what your stream did — not just what it emitted, but <strong>how and when it ended</strong>.</li></ul><p>dematerialize() is the <strong>reverse of </strong><strong>materialize()</strong>. It takes those Notification objects (which represent .next, .error, and .complete as data) and <strong>restores them back into real Observable behavior</strong>.</p><h3>Why use it?</h3><p>Imagine you used materialize() to treat errors like normal data — maybe to delay, log, or filter them. Now you want to <strong>turn that data back into actual stream behavior</strong>. That’s where dematerialize() comes in.</p><p>materialize() &amp; dematerialize() = Full control over <strong>both behavior and timing</strong> of emissions, errors, and completion.</p><blockquote>2.SubscribeOn</blockquote><p>subscribeOn() delays your stream’s start until after the page finishes its current work—so your UI can render first, then your heavy logic or API call runs.</p><p>In Simple Words:</p><blockquote><strong><em>subscribeOn(scheduler) moves the subscription side-effects to the given scheduler.</em></strong><em><br> This is useful when you want to offload heavy setup logic away from Angular&#39;s main thread.</em></blockquote><h3>Why use it?</h3><ul><li>Keeps the UI smooth by running heavy tasks a moment later.</li><li><strong>Ensures Angular’s initial render isn’t blocked</strong>, improving perceived performance.</li></ul><h3>Real Case Scenario:</h3><h4>🧾 Scenario: Heavy Calculation Before API Call</h4><p>Imagine you’re creating a report feature in Angular. Before hitting the API, you need to:</p><ul><li>read and filter a big local dataset (maybe from localStorage or indexedDB),</li><li>then prepare a large payload,</li><li>and finally send that to the backend.</li></ul><p>Normally, this whole chain might <strong>block the UI</strong> if done on the main thread.<br>But uisng SubscribeOn :</p><pre>import { asyncScheduler, of } from &#39;rxjs&#39;;<br>import { subscribeOn, map, switchMap } from &#39;rxjs/operators&#39;;<br><br>getPreparedData() {<br>  return of(null).pipe(<br>    subscribeOn(asyncScheduler), // move subscription logic to async queue<br>    map(() =&gt; {<br>      // heavy processing<br>      const raw = localStorage.getItem(&#39;large-dataset&#39;);<br>      const parsed = JSON.parse(raw || &#39;[]&#39;);<br>      return parsed.filter(item =&gt; item.active);<br>    }),<br>    switchMap(filteredData =&gt;<br>      this.http.post(&#39;/api/report&#39;, { data: filteredData })<br>    )<br>  );<br>}</pre><blockquote>3.<em>observeOn</em></blockquote><p>observeOn() postpones <strong>when and where</strong> each value (next/error/complete) is sent to your subscriber—so you can do heavy work off the main thread or bring results back into Angular’s zone <strong>after</strong> the current tasks finish.</p><p>In Simple Words:</p><blockquote><strong>observeOn(scheduler)</strong> shifts all downstream notifications onto the given scheduler. Use it to control exactly <strong>when</strong> and <strong>on which task queue</strong> your subscriber sees the values—without changing how the source Observable works.</blockquote><p>The key difference from subscribeOn is that, subscribeOn defers the <strong>entire</strong> stream to a given scheduler, whereas observeOn can shift execution <strong>mid‑stream</strong>, affecting only downstream notifications.</p><blockquote>4. GroupBy</blockquote><p>groupBy() splits a single stream into <strong>multiple grouped streams</strong> based on a key you provide. Each group becomes its own Observable that you can work with independently.</p><h3>Real Case Scenario:</h3><h4>🧾 Scenario: Grouping Live Notifications by Type</h4><p>Imagine you have a NotificationService that pushes a continuous stream of notifications into your app. You want to handle each notification type (info, warning, error) separately—for example, counting how many of each type have arrived in real time.</p><pre>import { from, groupBy, mergeMap, toArray } from &#39;rxjs&#39;;<br><br>interface Notification {<br>  type: &#39;info&#39; | &#39;warning&#39; | &#39;error&#39;;<br>  message: string;<br>}<br><br>from&lt;Notification&gt;([<br>  { type: &#39;info&#39;,    message: &#39;App started&#39;      },<br>  { type: &#39;warning&#39;, message: &#39;Low disk space&#39;   },<br>  { type: &#39;info&#39;,    message: &#39;User logged in&#39;   },<br>  { type: &#39;error&#39;,   message: &#39;Server not found&#39; }<br>]).pipe(<br>  groupBy(n =&gt; n.type),<br>  mergeMap(group$ =&gt; group$.pipe(toArray()))<br>)<br>.subscribe(grouped =&gt; console.log(grouped));</pre><h3>Expected Output:</h3><pre>[<br>  { type: &#39;info&#39;,    message: &#39;App started&#39;    },<br>  { type: &#39;info&#39;,    message: &#39;User logged in&#39; }<br>]<br>[<br>  { type: &#39;warning&#39;, message: &#39;Low disk space&#39; }<br>]<br>[<br>  { type: &#39;error&#39;,   message: &#39;Server not found&#39; }<br>]</pre><blockquote>5.<em>distinctUntilChanged</em></blockquote><p>Every value your stream emits may not be useful — especially when it keeps emitting the <strong>same</strong> thing again and again.<br> That’s where distinctUntilChanged() comes in: it <strong>only lets through values that are actually different</strong> from the last one.</p><pre>// getIsDiscountCodeAdded() will emit values only when <br>// previousValue !== currentValue.                   <br><br>setIsDiscountCodeAdded(value: boolean) {<br>  this.isDiscountCodeAdded.next(value);<br>}<br><br>getIsDiscountCodeAdded(): Observable&lt;boolean&gt; {<br>  return this.isDiscountCodeAdded.pipe(distinctUntilChanged());<br>}</pre><blockquote>6.<em>distinctUntilKeyChanged</em></blockquote><p>When your stream emits objects, but you only care about changes to <strong>a specific field</strong>, distinctUntilKeyChanged(key) helps you ignore all repeated values for that key.</p><pre>// getCurrentUser() will emit values only when<br>// previousUser.name !== currentUser.name<br><br>private currentUserSubject = new BehaviorSubject&lt;{ id: number; name: string; role: string }&gt;({<br>  id: 1,<br>  name: &#39;Rachit&#39;,<br>  role: &#39;viewer&#39;<br>});<br><br>setCurrentUser(user: { id: number; name: string; role: string }) {<br>  this.currentUserSubject.next(user);<br>}<br><br>getCurrentUser(): Observable&lt;{ id: number; name: string; role: string }&gt; {<br>  return this.currentUserSubject.pipe(<br>    distinctUntilKeyChanged(&#39;name&#39;)<br>  );<br>}</pre><p>Even if id or role changes, it will <strong>only emit when the </strong><strong>name value changes</strong> from the last emitted object.</p><blockquote>7.<em>onErrorResultNext</em></blockquote><p>Normally, if one Observable throws an error, the stream dies.<br>But what if you want to <strong>ignore the error</strong> and <strong>move on to another stream</strong>?<br>That’s exactly what onErrorResumeNext does.</p><p>If the current stream <strong>errors out</strong>, onErrorResumeNext() will quietly <strong>skip the error</strong> and move on to the <strong>next Observable</strong>—no catch blocks, no drama.</p><p><strong>Use‑case:</strong> <br>Try a primary HTTP endpoint, and if it errors, silently fall back to a secondary endpoint without interrupting the user flow.</p><pre>onErrorResumeNext(<br>  this.http.get(&#39;/api/primary&#39;),<br>  this.http.get(&#39;/api/backup&#39;)<br>).subscribe(data =&gt; this.handle(data));</pre><blockquote>8.<em>takeUntil</em></blockquote><p>You start an Observable — like a timer, an HTTP polling request, or a value stream. But <strong>how and when do you stop it?</strong><br>That’s where takeUntil() came in play, it automatically <strong>completes</strong> your Observable when another Observable emits.</p><blockquote><strong><em>In simple words, </em></strong>takeUntil(notifier$) means: <br><strong><em>listening</em></strong><em> until </em><em>notifier$ says </em><strong><em>&quot;Stop!&quot;</em></strong></blockquote><p>The most common used case of this operator is <br><strong>Auto-unsubscribe on component destroy</strong></p><pre>private destroy$ = new Subject&lt;void&gt;();<br><br>ngOnInit() {<br>  this.form.valueChanges.pipe(<br>    takeUntil(this.destroy$)  // stops when destroy$ emits<br>  ).subscribe(value =&gt; {<br>    console.log(&#39;Form changed:&#39;, value);<br>  });<br>}<br><br>ngOnDestroy() {<br>  this.destroy$.next();      // triggers completion<br>  this.destroy$.complete();  // clean up<br>}</pre><blockquote>9.<em>exhaustMap</em></blockquote><p>When the user clicks a button <strong>multiple times</strong>, you don’t want to trigger <strong>multiple API calls</strong> at once, right?<br> exhaustMap helps you <strong>ignore all new events</strong> until the current one finishes.</p><blockquote><strong><em>In simple words, <br></em></strong>If I’m busy, I ignore everything else until I’m done.<br> <strong>Only the first call is allowed.</strong> The rest are ignored until it completes.</blockquote><h3>Real Case Scenario:</h3><h4>🧾 Scenario: Prevent double-submits</h4><p>Let’s say you have a “Place Order” button and want to ensure the user doesn’t send multiple API calls by clicking repeatedly:</p><pre>placeOrderClick$ = new Subject&lt;void&gt;();<br><br>ngOnInit() {<br>  this.placeOrderClick$.pipe(<br>    exhaustMap(() =&gt; this.http.post(&#39;/api/place-order&#39;, {}))<br>  ).subscribe({<br>    next: res =&gt; console.log(&#39;Order placed!&#39;),<br>    error: err =&gt; console.error(&#39;Error:&#39;, err)<br>  });<br>}<br><br>// In template:<br>// &lt;button (click)=&quot;placeOrderClick$.next()&quot;&gt;Place Order&lt;/button&gt;</pre><h3>Explanation:</h3><p>1. Only <strong>the first click</strong> will trigger the API call.<br>2. All other clicks <strong>during the ongoing request</strong> will be ignored.<br>3. After the request finishes, the next click will be allowed.</p><blockquote>10.<em>race</em></blockquote><p>Imagine you have <strong>multiple Observables</strong>, and you only want to use the result of <strong>whichever finishes first</strong> — and <strong>ignore the rest</strong>.</p><p>That’s exactly what race() does: it listens to all given Observables and <strong>only lets the fastest one win</strong>. Once one emits, it <strong>cancels</strong> the others.</p><h3>Real Case Scenario:</h3><h4>🧾 Scenario: Fastest API fallback strategy</h4><p>Let’s say you have two APIs that can return the same data (like a cached version and a live version). You want to <strong>use whichever responds first</strong>.</p><pre>import { race, of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>const fromCache$ = of(&#39;from cache&#39;).pipe(delay(300));<br>const fromApi$   = of(&#39;from API&#39;).pipe(delay(100)); // faster<br><br>race(fromCache$, fromApi$).subscribe(result =&gt; {<br>  console.log(&#39;Winner:&#39;, result); // &quot;Winner: from API&quot;<br>});</pre><h3>Use Cases:</h3><ul><li>Load-balancing between APIs (CDN vs server)</li><li>Selecting the fastest network mirror</li><li>Reducing latency in fallback strategies</li><li>Picking between cache, local DB, or remote API</li></ul><p>You can even <strong>race</strong> <strong>user events</strong>:</p><pre>race(<br>  fromEvent(document, &#39;click&#39;),<br>  fromEvent(document, &#39;keydown&#39;)<br>).subscribe(event =&gt; {<br>  console.log(&#39;User acted first with:&#39;, event.type);<br>});</pre><h3>Angular + RxJS isn’t just reactive — it can be proactive. These operators are how you level up.</h3><blockquote>Have you used any of these RxJS operators in your projects?<br>Got a unique use case, a smart workaround, or know another underrated operator that deserves attention?</blockquote><blockquote>Drop it in the comments — let’s educate each other and become better developers together.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909586e694d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>