<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Md Nafish Alam</title>
    <description>The latest articles on DEV Community by Md Nafish Alam (@md_nafishalam_58b9fca2a5).</description>
    <link>https://dev.to/md_nafishalam_58b9fca2a5</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3200487%2Fcf499d1e-93a6-4958-aa17-273e35daaf5a.jpg</url>
      <title>DEV Community: Md Nafish Alam</title>
      <link>https://dev.to/md_nafishalam_58b9fca2a5</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/md_nafishalam_58b9fca2a5"/>
    <language>en</language>
    <item>
      <title>Netflix vs. Live Broadcast: Understanding Cold and Hot Observables in RxJS 7</title>
      <dc:creator>Md Nafish Alam</dc:creator>
      <pubDate>Sat, 21 Jun 2025 09:22:16 +0000</pubDate>
      <link>https://dev.to/md_nafishalam_58b9fca2a5/netflix-vs-live-broadcast-understanding-cold-and-hot-observables-in-rxjs-7-21h9</link>
      <guid>https://dev.to/md_nafishalam_58b9fca2a5/netflix-vs-live-broadcast-understanding-cold-and-hot-observables-in-rxjs-7-21h9</guid>
      <description>&lt;p&gt;&lt;em&gt;In the world of Angular development, particularly when dealing with asynchronous operations, RxJS is your best friend .But sometimes, RxJS concept can feel a bit abstract. Today let's demystify two fundamental concepts. &lt;strong&gt;Cold and Hot Observables&lt;/strong&gt;.&lt;/em&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Cold Observables: The On-Demand performers
&lt;/h2&gt;

&lt;p&gt;Imagine a &lt;strong&gt;Cold Observables&lt;/strong&gt; like a movie on Netflix. When you click play, a new instance of that movie starts just for you. If your friend clicks play on the same movie, they get their own independent stream from the beginning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What it is:&lt;/strong&gt; A Cold Observable starts producing value when a new subscriber subscribes to it. Each subscriber gets its own independent execution of the observable's underlying producer function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Its Character:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Laxy:&lt;/strong&gt;  It doesn't do any work until explicitly asked(subscribed to).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Independent:&lt;/strong&gt; Each subscription triggers a new , separate execution of the Observable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Reproducible:&lt;/strong&gt; The sequence of value is typically the same for each subscriber, starting from the beginning.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Real-World Examples When to Use it:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;HTTP Requests:&lt;/strong&gt; This is the most common example. When you make an

&lt;code&gt;HttpClient.get()&lt;/code&gt;

request in Angular, it's a Cold Observable. Each time you subscribe, a new HTTP request is sent to the server.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Each subscription sends a new GET request&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/api/data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Subscriber 1:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/api/data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Subscriber 2:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;DOM Events:&lt;/strong&gt; While DOM events can be hot if using

&lt;code&gt;fromEvent&lt;/code&gt;

directly on an existing element, if you're setting up an event listener based on a new element's creation, it's often cold.&lt;/li&gt;
&lt;/ul&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Timer/Intervals (unshared):&lt;/strong&gt; If you create a

&lt;code&gt;timer&lt;/code&gt;

or

&lt;code&gt;interval&lt;/code&gt;

observable and subscribe multiple times without sharing, each subscription gets its own independent timer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Hot Observables: The Live Broadcast
&lt;/h2&gt;

&lt;p&gt;Now, think of a &lt;strong&gt;Hot Observable&lt;/strong&gt; like a live radio broadcast or a YouTube livestream. The broadcast is happening continuously, regardless of whether anyone is tuned in. If you tune in late, you'll join the stream in progress, you won't hear what's already been played.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What it is:&lt;/strong&gt; A Hot Observable is already producing values before any subscriber subscribes to it. Subscribers simply listen to the ongoing streams of values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Its Character:&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Active:&lt;/strong&gt; It's pushing values whether or not there are any listeners.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Shared:&lt;/strong&gt; All subscribers share the same execution of the Observable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Irreproducible(from the start):&lt;/strong&gt; Subscribers might miss initial values if they subscribe late.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Real-World Examples When to Use it:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;User Input Events (Shared):&lt;/strong&gt; If you have a global search input and multiple components need to react to its changes, you'd typically make this a Hot Observable using

&lt;code&gt;shareReplay()&lt;/code&gt;

or

&lt;code&gt;share()&lt;/code&gt;

.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Subject&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="c1"&gt;// Imagine this is a service, e.g., search.service.ts&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SearchService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;searchInputSubject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;Subject&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

  &lt;span class="c1"&gt;// Expose the Subject as an Observable for components to subscribe to&lt;/span&gt;
  &lt;span class="nx"&gt;searchInput$&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchInputSubject&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;asObservable&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

  &lt;span class="c1"&gt;// Method to emit new search terms&lt;/span&gt;
  &lt;span class="nf"&gt;updateSearchTerm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;term&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`SearchService: Emitting new term: "&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;term&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchInputSubject&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;term&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// --- How this would be used in your Angular components ---&lt;/span&gt;

&lt;span class="c1"&gt;// Assume SearchService is injected into your components' constructors&lt;/span&gt;
&lt;span class="c1"&gt;// constructor(private searchService: SearchService) {}&lt;/span&gt;

&lt;span class="c1"&gt;// In Component A's ngOnInit() or a similar lifecycle hook&lt;/span&gt;
&lt;span class="c1"&gt;// Component A subscribes&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchInput$&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;term&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Component A received:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;term&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="c1"&gt;// Update UI or perform filtering based on the term&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="c1"&gt;// In Component B's ngOnInit() (subscribing a little later)&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchInput$&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;term&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Component B received:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;term&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="c1"&gt;// Perhaps update a different part of the UI&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;WebSockets:&lt;/strong&gt;  A WebSocket connection is inherently hot. Data is being streamed from the server continuously, and any client that connects simply starts receiving the current flow of data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Stock Ticker Update:&lt;/strong&gt;  A continuous stream of stock prices would be a Hot Observable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;BehaviorSubject&lt;/code&gt;, &lt;code&gt;ReplaySubject&lt;/code&gt;, &lt;code&gt;Subject&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt; These are built-in RxJS constructs that are inherently hot. They are designed to multicasting values to multiple observers.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The Key Difference: When Does the Work Begin?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The fundamental difference boils down to _ &lt;strong&gt;when the Observable's "work" or "data production" begins relative to a subscription:&lt;/strong&gt;_&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cold:&lt;/strong&gt;Work begins on subscription. Each subscription gets its own, fresh start.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Hot:&lt;/strong&gt; Work is already in progress. Subscribers connect to an existing stream.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When to Make a Cold Observable Hot&lt;/strong&gt;&lt;br&gt;
Sometimes, you start with a Cold Observable (like an HTTP request) but realize you need to make it Hot because multiple parts of your application need the same data without triggering multiple backend calls. This is where multicasting operators come in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;share()&lt;/code&gt;:&lt;/strong&gt; operator in RxJS is a powerful tool used to convert a unicast (cold) Observable into a multicast (hot) Observable. By default, Observables are "&lt;strong&gt;cold&lt;/strong&gt;," meaning each subscription triggers a new, independent execution of the Observable's producer function. Subsequent subscribers will share the same underlying execution. If all subscribers unsubscribe, the source observable will be unsubscribed from, and a new subscription will restart the source observable for the next subscriber.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;ShareReplay()&lt;/code&gt;:&lt;/strong&gt; Similar to &lt;code&gt;share()&lt;/code&gt;, but it also replays a specified number of past values to new subscribers. Ideal for scenarios where new subscribers need the "last known" state immediately.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Example: Making an HTTP request hot with shareReplay&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;data$&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/api/data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="nf"&gt;shareReplay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// Cache the last value and share the stream&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Both subscribers get the data from a single HTTP request&lt;/span&gt;
&lt;span class="nx"&gt;data$&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Subscriber 1 received:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="nx"&gt;data$&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Subscriber 2 received:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Understanding Cold and Hot Observables is crucial for writing robust and efficient RxJS code in Angular. It helps you anticipate side effects, optimize network calls, and design more predictable data flows. While Cold Observables are the default and often what you start with, knowing when and how to transform them into Hot Observables with multicasting operators is a powerful skill in your RxJS toolkit. So, the next time you're working with Observables, ask yourself: does this need to be on-demand (cold) or a live broadcast (hot)? Your answer will guide you to cleaner, more effective solutions.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>rxjs</category>
      <category>angular</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>Why memory Leaks</title>
      <dc:creator>Md Nafish Alam</dc:creator>
      <pubDate>Sat, 24 May 2025 17:33:05 +0000</pubDate>
      <link>https://dev.to/md_nafishalam_58b9fca2a5/why-memory-leaks-1jhb</link>
      <guid>https://dev.to/md_nafishalam_58b9fca2a5/why-memory-leaks-1jhb</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg" class="crayons-story__hidden-navigation-link"&gt;Is Your Web App Leaking? A Beginner's Guide to Finding and Fixing Memory Issues (Part 1)&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/md_nafishalam_58b9fca2a5" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3200487%2Fcf499d1e-93a6-4958-aa17-273e35daaf5a.jpg" alt="md_nafishalam_58b9fca2a5 profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/md_nafishalam_58b9fca2a5" class="crayons-story__secondary fw-medium m:hidden"&gt;
              Md Nafish Alam
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                Md Nafish Alam
                
              
              &lt;div id="story-author-preview-content-2519292" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/md_nafishalam_58b9fca2a5" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3200487%2Fcf499d1e-93a6-4958-aa17-273e35daaf5a.jpg" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;Md Nafish Alam&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;May 24 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg" id="article-link-2519292"&gt;
          Is Your Web App Leaking? A Beginner's Guide to Finding and Fixing Memory Issues (Part 1)
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/webdev"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;webdev&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/javascript"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;javascript&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/devtools"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;devtools&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/memoryleaks"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;memoryleaks&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
          &lt;a href="https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left"&gt;
            &lt;div class="multiple_reactions_aggregate"&gt;
              &lt;span class="multiple_reactions_icons_container"&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/sparkle-heart-5f9bee3767e18deb1bb725290cb151c25234768a0e9a2bd39370c382d02920cf.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
              &lt;/span&gt;
              &lt;span class="aggregate_reactions_counter"&gt;2&lt;span class="hidden s:inline"&gt; reactions&lt;/span&gt;&lt;/span&gt;
            &lt;/div&gt;
          &lt;/a&gt;
            &lt;a href="https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              2&lt;span class="hidden s:inline"&gt; comments&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            6 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>devtools</category>
      <category>memoryleaks</category>
    </item>
    <item>
      <title>Is Your Web App Leaking? A Beginner's Guide to Finding and Fixing Memory Issues (Part 1)</title>
      <dc:creator>Md Nafish Alam</dc:creator>
      <pubDate>Sat, 24 May 2025 06:44:30 +0000</pubDate>
      <link>https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg</link>
      <guid>https://dev.to/md_nafishalam_58b9fca2a5/is-your-web-app-leaking-a-beginners-guide-to-finding-and-fixing-memory-issues-part-1-chg</guid>
      <description>&lt;p&gt;Ever noticed your web application getting sluggish over time? Or maybe it occasionally crashes for seemingly no reason? You might have a memory leak on your hands!&lt;/p&gt;

&lt;p&gt;In the world of web development, especially with complex JavaScript frameworks, memory leaks can be sneaky culprits. They happen when your application holds onto memory it no longer needs. Over time, this unused memory builds up, slowing everything down and potentially leading to a frustrating crash for your users.&lt;/p&gt;

&lt;p&gt;But don't worry! Detecting and fixing these leaks isn't some arcane art. In this first part of our guide (inspired by Metenski's excellent video on Decoded Frontend.), we'll explore the basics of memory leaks in web applications and introduce you to powerful tools in your browser's developer arsenal.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Exactly is a Memory Leak?
&lt;/h2&gt;

&lt;p&gt;A memory leak occurs when your application forgets to erase some of this information. It keeps holding onto it, even though it's no longer being used. Imagine leaving old notes all over the whiteboard – eventually, you'll run out of space!&lt;/p&gt;

&lt;p&gt;In JavaScript, the language powering most web applications, there's a clever system called "garbage collection" that automatically tries to clean up this unused memory. However, leaks happen when unintended connections or "references" prevent the garbage collector from doing its job.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common Culprits:Accidental Global Variables:
&lt;/h2&gt;

&lt;p&gt;If you forget to declare a variable with &lt;strong&gt;let, const, or var&lt;/strong&gt; inside a function, it can accidentally become a global variable. Global variables stick around for the entire lifespan of your application, potentially holding onto unnecessary data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doSomething() {
  message = "Hello!"; // Oops! 'message' becomes a global variable
  console.log(message);
}
doSomething();
console.log(message); // Still accessible globally!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Forgotten Timers and Intervals:
&lt;/h2&gt;

&lt;p&gt;If you set up a &lt;strong&gt;setTimeout or setInterval&lt;/strong&gt; function to run code repeatedly, and you don't clear it with &lt;strong&gt;clearTimeout or clearInterval&lt;/strong&gt; when you're done with it, these functions can keep your application alive and prevent associated data from being garbage collected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let intervalId = setInterval(() =&amp;gt; {
  console.log("This keeps running...");
}, 1000);

// If we don't do this:
// clearInterval(intervalId);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Dangling Event Listeners:
&lt;/h2&gt;

&lt;p&gt;When you add event listeners (like responding to a button click) to elements in your web page, and then you remove those elements from the page, the event listeners might still be hanging around in the background, holding references to the removed elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const button = document.getElementById('myButton');
function handleClick() {
  console.log('Button clicked!');
}
button.addEventListener('click', handleClick);

// Later, if the button is removed from the DOM:
// button.remove();
// The event listener might still be in memory if not explicitly removed:
// button.removeEventListener('click', handleClick);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Closures Holding Onto Too Much:
&lt;/h2&gt;

&lt;p&gt;Closures in JavaScript are powerful, but if a function's inner scope (its "closure") retains access to large amounts of data even after the outer function has finished executing, it can lead to memory buildup.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunction(largeData) {
  return function innerFunction() {
    console.log('Data is still here:', largeData.length);
    // Even after outerFunction finishes, innerFunction can still access largeData
  };
}

const bigData = new Array(1000000).fill('*');
const closure = outerFunction(bigData);
// Even if we don't call closure immediately, it 'remembers' bigData
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are different types of leaks too. Some, called "static leaks," might have a fixed size. But the more concerning ones are "dynamic leaks," which grow over time as the user interacts with the application, eventually leading to noticeable performance issues or crashes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Becoming a Memory Leak Detective: Your Debugging Toolkit
&lt;/h2&gt;

&lt;p&gt;The good news is that modern web browsers come equipped with fantastic developer tools to help you track down these memory gremlins. We'll focus on Google Chrome's DevTools in this guide.&lt;/p&gt;

&lt;p&gt;Before we dive into the tools, here are a few good practices to keep in mind:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Incognito Mode:&lt;/strong&gt; This ensures a clean testing environment without browser extensions potentially interfering.&lt;br&gt;
&lt;strong&gt;Test Your Production Build:&lt;/strong&gt; Sometimes, optimizations in your development build can mask memory issues that only appear in the final, production version.&lt;br&gt;
&lt;strong&gt;For Angular Users (and other frameworks with build processes):&lt;/strong&gt; Consider temporarily disabling variable name mangling during your build process. This can make it much easier to understand object names in the DevTools.&lt;br&gt;
Now, let's peek into the essential DevTools tabs for memory leak hunting:&lt;/p&gt;
&lt;h2&gt;
  
  
  1. The Performance Tab: Getting the Big Picture
&lt;/h2&gt;

&lt;p&gt;The Performance tab gives you a timeline of your application's activity. When investigating memory, look for the &lt;strong&gt;"JS heap"&lt;/strong&gt; graph (usually a blue line). This graph shows how much memory your JavaScript code is using over time.&lt;/p&gt;

&lt;p&gt;A healthy application will show this line fluctuating – memory goes up when new things are created, and then dips down when the garbage collector kicks in and reclaims unused memory.&lt;/p&gt;

&lt;p&gt;However, if you see the &lt;strong&gt;"JS heap"&lt;/strong&gt; line steadily increasing over time, without significant dips even after periods of inactivity, this is a strong indicator of a potential memory leak. The memory just keeps growing, suggesting that something isn't being released properly.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. The Memory Tab: Diving into the Details
&lt;/h2&gt;

&lt;p&gt;The Memory tab provides more specific tools for examining your application's memory usage at a granular level. Here are the key instruments:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Heap Snapshots:&lt;/strong&gt; Imagine taking a freeze-frame picture of all the objects and data currently residing in your application's memory. Heap snapshots allow you to do just that. You can take multiple snapshots at different points in your application's lifecycle and then compare them to see what objects are being created and, crucially, what objects are not being cleaned up. By comparing snapshots before and after performing a specific action in your app, you can identify objects that are accumulating unexpectedly. Look for a positive "Delta" – more objects created than deleted. Consistent patterns across multiple tests can strengthen your suspicion of a leak. You can also inspect the "Retainers" of an object to see what other objects are holding onto it, preventing it from being garbage collected.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Allocations on Timeline:&lt;/strong&gt; This tool tracks memory allocations in real-time as you interact with your application. As you perform actions like navigating between pages or interacting with components, you'll see spikes in memory usage. This can help you pinpoint which actions are leading to memory being allocated. More importantly, you can see if the allocated memory is being freed afterward. Look for objects that show a consistently growing "Allocated Size" – this could be a sign that those objects are not being properly released.&lt;/p&gt;

&lt;p&gt;By using these tools and carefully observing how your application's memory behaves, you can start to identify those sneaky memory leaks.&lt;/p&gt;
&lt;h2&gt;
  
  
  A Real-World Example: The Case of the Lingering Subscription
&lt;/h2&gt;

&lt;p&gt;Metenski's video provides a great example of a common memory leak in Angular applications: an RxJS subscription that isn't properly unsubscribed when a component is destroyed. This means that even after the component is no longer visible on the screen, the subscription is still active in the background, holding onto the component's instance and preventing it from being garbage collected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-leaky',
  template: `&amp;lt;div&amp;gt;Leaky Component&amp;lt;/div&amp;gt;`,
})
export class LeakyComponent implements OnInit, OnDestroy {
  private intervalSubscription: Subscription | undefined;
  private destroy$ = new Subject&amp;lt;void&amp;gt;();

  ngOnInit(): void {
    this.intervalSubscription = interval(1000)
      .pipe(takeUntil(this.destroy$)) // Prevents leak
      .subscribe(() =&amp;gt; {
        console.log('Tick...');
      });
  }

  ngOnDestroy(): void {
    // Without this, the subscription would likely persist, causing a memory leak
    if (this.intervalSubscription) {
      this.intervalSubscription.unsubscribe();
    }
    this.destroy$.next();
    this.destroy$.complete();
  }
}

@Component({
  selector: 'app-fixed',
  template: `&amp;lt;div&amp;gt;Fixed Component&amp;lt;/div&amp;gt;`,
})
export class FixedComponent implements OnInit, OnDestroy {
  private intervalSubscription: Subscription | undefined;

  ngOnInit(): void {
    this.intervalSubscription = interval(1000).subscribe(() =&amp;gt; {
      console.log('Tick (fixed)...');
    });
  }

  ngOnDestroy(): void {
    if (this.intervalSubscription) {
      this.intervalSubscription.unsubscribe();
    }
  }
}

// Newer Angular versions often recommend using takeUntilDestroyed:
// import { takeUntilDestroyed } from '@angular/core/rxjs';
// ...
// ngOnInit(): void {
//   interval(1000)
//     .pipe(takeUntilDestroyed(this.destroyRef))
//     .subscribe(() =&amp;gt; {
//       console.log('Tick (modern Angular)...');
//     });
// }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The solution? Using operators like &lt;strong&gt;takeUntilDestroyed&lt;/strong&gt; (available in newer versions of Angular) or manually unsubscribing in the component's &lt;strong&gt;ngOnDestroy&lt;/strong&gt; lifecycle hook ensures that the subscription is cleaned up when the component is no longer needed, preventing the memory leak.&lt;/p&gt;

&lt;h2&gt;
  
  
  What's Next?
&lt;/h2&gt;

&lt;p&gt;This is just the beginning of our journey into the world of memory leak detection! In the next part of this guide , we'll delve into another common type of memory leak: detached DOM elements – elements that are no longer attached to the visible page but are still being held in memory.&lt;/p&gt;

&lt;p&gt;So, keep an &lt;strong&gt;eye out for Part 2,&lt;/strong&gt; and in the meantime, start experimenting with the Performance and Memory tabs in your browser's DevTools. Happy debugging!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>devtools</category>
      <category>memoryleaks</category>
    </item>
  </channel>
</rss>
