<?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 Areg Sargsyan on Medium]]></title>
        <description><![CDATA[Stories by Areg Sargsyan on Medium]]></description>
        <link>https://medium.com/@Areg_Sargsyan?source=rss-a227d815bfe6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TqKGK2N4SRqBY5BPPm9yTw.jpeg</url>
            <title>Stories by Areg Sargsyan on Medium</title>
            <link>https://medium.com/@Areg_Sargsyan?source=rss-a227d815bfe6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:06:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Areg_Sargsyan/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[REST vs gRPC: Why High-Load Systems Are Moving to Binary APIs]]></title>
            <link>https://medium.com/swlh/rest-vs-grpc-why-high-load-systems-are-moving-to-binary-apis-73f7bc59777c?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f7bc59777c</guid>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 22:53:20 GMT</pubDate>
            <atom:updated>2026-03-16T22:53:20.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*thMl2ePODKQh__9vuxk7cg.png" /></figure><h3>What Is REST?</h3><p>REST (Representational State Transfer) is an architectural style for building APIs using standard HTTP methods.</p><p>Typical REST APIs use:</p><ul><li>HTTP/1.1</li><li>JSON payloads</li><li>resource-based endpoints</li></ul><p>Example:</p><p>GET /users/10</p><p>Response:</p><pre>{<br> “id”: 10,<br> “name”: “Areg”<br> }</pre><p>REST is easy to understand and works well for public APIs. However, it has limitations in high-load distributed systems.</p><h3>What Is gRPC?</h3><p>gRPC (Google Remote Procedure Call) is a framework that allows services to call methods on remote servers as if they were local functions.</p><p>APIs are defined using Protocol Buffers.</p><pre>service UserService {<br>  rpc GetUser(UserRequest) returns (UserResponse);<br>}<br><br>message UserRequest {<br>  int32 id = 1;<br>}<br><br>message UserResponse {<br>  string name = 1;<br>}</pre><p>From this file, client and server code are generated automatically.</p><h3>The Key Difference: Text vs Binary</h3><p>REST uses JSON (text-based):</p><p>gRPC uses Protocol Buffers (binary format):</p><ul><li>smaller payload size</li><li>faster serialization</li><li>faster deserialization</li></ul><p>In high-load systems, this matters a lot.</p><p>👉 Less data over the network = lower latency<br> 👉 Faster parsing = lower CPU usage</p><p>In many cases, payload size is reduced by <strong>3–10x</strong>.</p><h3>HTTP/1.1 vs HTTP/2</h3><p>REST → HTTP/1.1<br> gRPC → HTTP/2</p><p>HTTP/2 introduces:</p><h3>Multiplexing</h3><p>Multiple requests share one connection.</p><p>Instead of:</p><blockquote>request → response<br>request → response</blockquote><p>You get:</p><blockquote>request1<br>request2<br>request3</blockquote><p>This is critical in high-load systems where services constantly communicate.</p><h3>Header Compression</h3><p>Headers are compressed, reducing overhead.</p><h3>Streaming</h3><p>gRPC supports:</p><ul><li>Unary</li><li>Server streaming</li><li>Client streaming</li><li>Bidirectional streaming</li></ul><p>This allows real-time data without repeated HTTP calls.</p><h3>Why gRPC Is Faster (Especially Under High Load)</h3><p>In low-load systems, the difference between REST and gRPC might be small.</p><p>But under high load, the difference becomes significant.</p><p>gRPC reduces:</p><ul><li>network usage</li><li>CPU overhead</li><li>connection overhead</li></ul><p>Which leads to:</p><ul><li>lower latency</li><li>higher throughput</li><li>better scalability</li></ul><h3>Performance Benchmarks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUhExelPWgWpjS5TTUcgTg.png" /></figure><p>Example:</p><ul><li>JSON: ~1KB</li><li>protobuf: ~200–400 bytes</li></ul><p>At scale, this difference becomes massive.</p><h3>Why gRPC Is Ideal for Microservices</h3><p>A typical microservice request flow:</p><blockquote>API Gateway<br> ↓<br>User Service<br> ↓<br>Payment Service<br> ↓<br>Notification Service</blockquote><p>Each step adds latency.</p><p>In high-load environments:</p><ul><li>1 request → 5–10 internal calls</li><li>thousands of users → millions of internal calls</li></ul><p>gRPC improves this by:</p><ul><li>reducing payload size</li><li>using persistent connections</li><li>enabling parallel communication (HTTP/2)</li><li>enforcing strong contracts</li></ul><h3>gRPC in the Browser</h3><p>Browsers support HTTP/2 but do not expose low-level HTTP/2 frame control required by gRPC.</p><p>That’s why gRPC-Web is used.</p><blockquote>Browser<br> ↓<br>gRPC-Web<br> ↓<br>Proxy (Envoy)<br> ↓<br>gRPC Server</blockquote><h3>Final Thoughts</h3><p>As systems scale, performance becomes critical.</p><p>The shift is clear:</p><ul><li>JSON → binary</li><li>HTTP/1.1 → HTTP/2</li><li>manual APIs → generated clients</li></ul><p>gRPC is not just faster — it is built for <strong>high-load distributed systems</strong>.</p><p>That’s why industries like <strong>iGaming, fintech, and real-time platforms</strong> are actively adopting it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f7bc59777c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/rest-vs-grpc-why-high-load-systems-are-moving-to-binary-apis-73f7bc59777c">REST vs gRPC: Why High-Load Systems Are Moving to Binary APIs</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shipping Features Safely: Progressive Rollouts with Feature Flags]]></title>
            <link>https://medium.com/swlh/shipping-features-safely-progressive-rollouts-with-feature-flags-9197e1291049?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9197e1291049</guid>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 15:35:38 GMT</pubDate>
            <atom:updated>2026-02-11T15:35:38.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3laUPc4g7-9f3hgC57y1Kg.png" /></figure><p>Releasing a new feature to 100% of users sounds simple. In reality, it’s one of the riskiest moments in a product’s lifecycle. A small bug can turn into thousands of broken sessions, support tickets, and lost revenue — especially in high-load, real-time platforms. This is why modern teams don’t simply “release”. They <strong>progressively roll out</strong>.</p><h3>The problem with big-bang releases</h3><p>Traditional releases often look like this:</p><ol><li>Merge to main</li><li>Deploy</li><li>Everyone gets the feature</li></ol><p>If something goes wrong:</p><ul><li>A hotfix is rushed</li><li>Or an entire release is rolled back</li></ul><p>Both options are slow and stressful.</p><p>In high-load systems, this model does not scale.</p><h3>Feature flags as a release mechanism</h3><p>Feature flags decouple <strong>deployment</strong> from <strong>exposure</strong>.</p><p>Instead of:</p><blockquote><em>Deploy to release a feature</em></blockquote><p>Teams move to:</p><blockquote><em>Deploy once, enable gradually</em></blockquote><p>Platforms like GrowthBook make this possible by providing percentage rollouts, targeting rules, and instant configuration updates without redeploying code.</p><h3>A typical progressive rollout strategy</h3><p>A common approach looks like this:</p><ol><li>Deploy feature code with flag disabled</li><li>Enable for internal users via GrowthBook</li><li>Enable for 50% of users</li><li>Monitor system health</li><li>Increase to 100% or roll back</li></ol><p>This turns releases into controlled, reversible operations.</p><h3>Observability makes rollouts meaningful</h3><p>Progressive rollout without observability is guesswork.</p><p>Teams typically monitor:</p><ul><li>Error rate</li><li>Performance metrics</li><li>User drop-offs</li><li>Business KPIs</li></ul><p>Only with this data can a team confidently decide whether a feature is safe to expand.</p><h3>Cultural impact</h3><p>After adopting progressive rollouts:</p><ul><li>Releases become routine</li><li>Fear decreases</li><li>Hotfixes drop</li><li>Engineers gain confidence</li></ul><p>Feature flags change not only architecture, but also engineering culture.</p><h3>Final thoughts</h3><p>Modern delivery is not about deploying faster.</p><p>It’s about <strong>exposing safely</strong>.</p><p>Progressive rollouts with feature flags turn releases into controlled, low-risk, reversible operations — and that changes everything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9197e1291049" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/shipping-features-safely-progressive-rollouts-with-feature-flags-9197e1291049">Shipping Features Safely: Progressive Rollouts with Feature Flags</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a ChatGPT-Powered Telegram Bot: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@Areg_Sargsyan/building-a-chatgpt-powered-telegram-bot-a-step-by-step-guide-cd89451c2c15?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd89451c2c15</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-and-machine-learning]]></category>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 16:09:00 GMT</pubDate>
            <atom:updated>2024-03-25T16:09:00.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxiYvJfmcKIh4XCtBIRz6g.jpeg" /><figcaption>OpenAI PoweredTelegram</figcaption></figure><p>As the world of AI-driven conversations continues to progress, ChatGPT emerges as a game-changer. It can produce text responses that resemble human language. Telegram, with its powerful bot API, provides an ideal platform for chatbots powered by AI. This guide will show you how to connect ChatGPT to a Telegram bot, enabling you to use conversational AI on one of the most popular messaging apps.</p><h3>Getting Started</h3><p>Before diving into the technical setup, ensure you have:</p><ul><li>An OpenAI API key from <a href="https://openai.com/"><strong>OpenAI</strong></a>.</li><li>A Telegram bot token, obtained by creating a bot through <strong>BotFather</strong> on Telegram.</li><li>Node.js installed on your system.</li></ul><h3>Step 1: Setting Up Your Project</h3><p>Initialize a Node.js project and install necessary packages:</p><pre>mkdir telegram-chatgpt-bot<br>cd telegram-chatgpt-bot<br>npm init -y<br>npm install dotenv openai node-telegram-bot-api</pre><h3>Step 2: Configuring the Environment</h3><p>Securing sensitive information, like your OpenAI API key and Telegram bot token, is crucial in any development project. Hardcoding these directly in your source code is risky and can lead to unauthorized access if exposed. This is where environment variables come into play, offering a secure and flexible way to handle sensitive data.</p><h3>Why Not Keep Keys in the Code?</h3><p>Storing keys directly in your code, especially when it’s shared or stored in version control (like GitHub), makes it easy for unauthorized users to access and misuse them. This can lead to security breaches and potential financial losses.</p><h3>Setting Up dotenv for Secure Key Management</h3><p><a href="https://www.npmjs.com/package/dotenv">dotenv</a> is a library that loads environment variables from a .env file into process.env, making them accessible in your Node.js application while keeping them out of your source code.</p><h4>Creating the .env File</h4><ol><li>Location: In the root directory of your project, create a file named .env. This is where you&#39;ll securely store your API keys.</li><li>Adding Tokens: Open the .env file in your text editor and add your OpenAI API key and Telegram bot token like so:</li></ol><pre>OPENAI_API_KEY=your_openai_api_key_here<br>TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here</pre><p>Replace your_openai_api_key_here and your_telegram_bot_token_here with your actual keys.</p><p>3. Using dotenv in Your Application: At the beginning of your main application file (e.g., bot.js), add the following code to load the environment variables:</p><pre>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();</pre><p>This makes process.env.OPENAI_API_KEY and process.env.TELEGRAM_BOT_TOKEN available throughout your application.</p><h3>Best Practices</h3><ul><li>Exclude .env from Version Control: To prevent exposing your sensitive information, ensure the .env file is listed in your .gitignore. This keeps it from being committed to version control.</li><li>Environment-Specific Files: If your project requires different configurations for development, testing, and production, you can create separate .env files (e.g., .env.production) for each environment.</li></ul><p>By following these steps, you ensure that your sensitive information is handled securely and flexibly, paving the way for a safer and more manageable project environment.</p><h3>Step 3: The Bot Code</h3><p>Here’s how you set up your bot:</p><pre>import OpenAI from &quot;openai&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>import TelegramBot from &quot;node-telegram-bot-api&quot;;<br><br>dotenv.config();<br><br>const openai = new OpenAI({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });<br><br>const conversations = new Map();<br><br>bot.on(&quot;message&quot;, async (msg) =&gt; {<br>  const chatId = msg.chat.id;<br>  const userInput = msg.text;<br><br>  // Initialize or update the conversation context, Isolating Conversations<br>  const messages = conversations.get(chatId) || [];<br>  messages.push({ role: &quot;user&quot;, content: userInput });<br><br><br>  try {<br>    const response = await openai.chat.completions.create({<br>      model: &quot;gpt-4&quot;,<br>      messages: messages,<br>      temperature: 1,<br>      max_tokens: 256,<br>      top_p: 1,<br>      frequency_penalty: 0,<br>      presence_penalty: 0,<br>      // response_format: { type: &quot;json_object&quot; },<br>    });<br><br>    messages.push(response.choices[0]?.message);<br><br>    conversations.set(chatId, messages); // Save the updated conversation context<br><br>    bot.sendMessage(chatId, response.choices[0]?.message.content);<br>  } catch (error) {<br>    console.error(&quot;Failed to fetch response from OpenAI:&quot;, error);<br>    bot.sendMessage(chatId, &quot;Oops! I encountered an error trying to respond.&quot;);<br>  }<br>});</pre><p>Run your bot with node bot.js, and your Telegram bot will come to life, ready to converse with users.</p><h3>Exploring Integration Alternatives: <a href="https://yourgpt.ai/">yourgpt.io</a></h3><p>While direct integration offers control and customisation,<a href="https://yourgpt.ai/"> ‘yourgpt.io’</a> presents a simpler, albeit paid, alternative. However, the hands-on approach detailed above not only saves costs but also enriches your understanding and capability to tailor the bot to your exact needs.</p><p>This guide aims to spark your creativity in using AI and messaging platforms. Feel free to ask questions or share ideas. Continue the discussion by connecting with me on <a href="https://www.linkedin.com/in/areg-sargsyan/">LinkedIn</a>. I’m open to future article suggestions as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd89451c2c15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Most Famous Error in Angular]]></title>
            <link>https://medium.com/@Areg_Sargsyan/the-most-famous-error-in-angular-28f15620690d?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/28f15620690d</guid>
            <category><![CDATA[lifecycle-hook]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[onpush]]></category>
            <category><![CDATA[changedetectorref]]></category>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 15:17:37 GMT</pubDate>
            <atom:updated>2024-03-04T17:39:01.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yotck0RRdV4XKf9-X8thVQ.png" /><figcaption>Understanding ExpressionChangedAfterItHasBeenCheckedError in Angular Development Mode</figcaption></figure><p>The Error “ExpressionChangedAfterItHasBeenCheckedError” is one of the most common and unclear errors in Angular and cannot always be recognized immediately. This confusion typically stems from a lack of understanding of Angular’s change detection mechanism. I recommend reading my previous article on Angular’s change detection algorithm for a deeper understanding. Knowing why this error check exists is crucial. More importantly, understanding the root cause of this error can help in correcting it, or even better, avoiding it altogether. Let’s take a closer look at the process involved in change detection.</p><p>First, let’s note that this error occurs only in ‘dev’ mode. Why? In development mode, Angular runs change detection twice to check if the value has changed since the first run. In production mode, change detection is only run once for better performance. Let’s see an example in <a href="https://stackblitz.com/github/AregSargsyan/ExpressionChangedAfterCheckedError/tree/master/changeDetection2">stackblitz</a>. I add “console.log” statements in lifecycle hooks and getters to detect the time (the place/order) when change detection exactly works. From the screen below, we can see that the afterViewInit and afterViewChecked lifecycle hooks are called after change detection, and after they are called, Angular runs change detection an additional second time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiR88w83DQZ6pcCY9dnsPg.jpeg" /><figcaption>Development mode</figcaption></figure><p>If we enable “prod” mode the second change detection run will not work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX_nT2oH1S7h6B_rjh2IqA.jpeg" /><figcaption>production mode</figcaption></figure><p>So, this error is a sign that you should refactor your code, as Angular warns you that this change in your model will not be picked up when enabling production mode! Let’s change the property “count” in the ngOnInit lifecycle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc3efc22fbbc698f6fdaf0fc29d101f4/href">https://medium.com/media/bc3efc22fbbc698f6fdaf0fc29d101f4/href</a></iframe><p>As you guessed, everything works fine. We change the property in the class before the change detection run, and after running change detection, the view also changes. <br>But what if we change the property “count” in afterViewInit?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb8259eef63e2761884721082dd4a0a8/href">https://medium.com/media/eb8259eef63e2761884721082dd4a0a8/href</a></iframe><p>In production mode, we will not find any error, but the count will not change. In development mode, we will see the famous Error “ExpressionChangedAfterItHasBeenCheckedError,” which tells us that there are changes that will not be visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzqwsXm1KAGxybWwwhNGpQ.jpeg" /></figure><p>In other words, Angular saw changes in your model that were caused by events, XHR requests, setTimeout, setInterval, etc., and then Angular ran change detection to update your view and re-render it. But then, there was another function in your code which updated the model, but change detection (in prod mode) will not run again because there is no “Digest cycle” like in AngularJS anymore.</p><h3>Ways to fix it</h3><ul><li><strong>move your code to ngOnInit()</strong></li></ul><p>Ensure that the update is inside the change detection cycle (Angular 2+ updates are a one-way flow that happens once; do not update the model after that and move your code to a better place/time).</p><p>Moving your code to ngOnInit or ngOnChanges (depending on the situation) will help because Angular will perform change detection only after these lifecycle hooks.</p><ul><li><strong>run change detection manually</strong></li></ul><p>There can be cases when moving code to ngOnInit is not possible. For example, you have to rely on ViewChild (ViewChild is accessible in AfterViewInit), or if some code should only run after Angular has fully initialized a component’s view. So, we need to run change detection manually, with one of the following variants:</p><ul><li>First, put the code inside a setTimeout, because setTimeout is patched by Zone and will run change detection after it’s finished.</li><li>Second, force change detection with ChangeDetectorRef.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dab5cb2ba2e6508c1a334b7582e98076/href">https://medium.com/media/dab5cb2ba2e6508c1a334b7582e98076/href</a></iframe><p>Second variant force change detection with ChangeDetectorRef</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/695e9ff36ece57dc05eaabb8e3a86e8c/href">https://medium.com/media/695e9ff36ece57dc05eaabb8e3a86e8c/href</a></iframe><h3>Conclusion</h3><p>In this article, we discussed the origin and meaning of the “ExpressionChangedAfterItHasBeenCheckedError” error and also discussed possible solutions to this problem depending on different situations.</p><p>Thank you for reading, and as always, if you have any questions, please feel welcome.</p><ul><li>Angular error solving</li><li>Angular change detection best practices</li><li>Debugging ExpressionChangedAfterItHasBeenCheckedError</li><li>Angular development tips</li><li>Angular development best practices</li><li>Debugging Angular applications</li><li>Change detection in Angular</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f15620690d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve performance of Angular application with Change Detection and NgZone]]></title>
            <link>https://medium.com/swlh/angular-change-detection-ngzone-a5103fab3866?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5103fab3866</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngzone]]></category>
            <category><![CDATA[onpush]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[change-detection]]></category>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 12:41:36 GMT</pubDate>
            <atom:updated>2023-10-09T20:26:24.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vb2UVEfYxNMG2TYojmIalw.jpeg" /></figure><h3>Change Detection</h3><p>We often hear as an argument for using frameworks something like “The framework will do everything for you — faster and more efficiently. You do not need to think about anything. Just manage the data.” Perhaps this is true with a very simple application. But if you have to work with user input and constantly operate on data knowing how the change detection and rendering process works is a must.</p><p>Change Detection is a mechanism that is responsible for checking changes in Angular. As a result of various operations such as changing the value of a class property, completing an asynchronous operation, the response of the HTTP request, initiating one of the browser events (for example ‘click’ event), etc — the change detection process starts from the root of the application’s component tree.</p><p>Since the main goal of the process is to understand how to re-render a component, it is essential to verify the data used in the templates : if it has changed then the template itself is marked as “changed” and will be re-rendered.</p><p>We can see this with a simple example. Every time we click on the button the component’s code updates only the property ‘count’ of the component. However the HTML is updated automatically.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>@Component({<br>    selector: &#39;app-root&#39;,<br>    template: `<br>        {{runChangeDetection}}<br>        &lt;div&gt;{{count}}&lt;/div&gt;<br>        &lt;button (click)=&quot;handler()&quot;&gt; ClickMe &lt;/button&gt;<br>    `<br>})<br>export class AppComponent {<br> <br>count = 0;</pre><pre>    get runChangeDetection() {<br>       console.log(&#39;Checking the view&#39;);<br>       return true;<br>     }</pre><pre>    handler() {<br>       this.count++;<br>       // user does not need to trigger change detection manually<br>    }<br>}</pre><p>To clarify when and how many times change detection is triggered we create a getter in the component and use it in our template. After each click Angular will start the change detection cycle and in the console we will see two logs “Checking the view” (or one in the production mode).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Finfatuatedsomearachnid&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Finfatuatedsomearachnid&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FInfatuatedSomeArachnid-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="450" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/c15156c25d2d7e331fad327a139808f8/href">https://medium.com/media/c15156c25d2d7e331fad327a139808f8/href</a></iframe><p>Moreover, change detection will be triggered even the button does nothing:</p><pre>handler() {<br>       <br>    }</pre><p>To clarify how changes are detected and values are updated, consider the following code written in plain JavaScript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e473c9e3f2dc4692143066a0ab26a45/href">https://medium.com/media/8e473c9e3f2dc4692143066a0ab26a45/href</a></iframe><p>After we update the data, we need to call detectChange() manually to check whether the data has changed or not. If the data has changed, we re-render the HTML to reflect the updated data.</p><p>In Angular, this steps are unnecessary. Whenever you update the data, your HTML is updated automatically.</p><p>A similar example of the change detection triggering can be seen in the example of a timer where every 100ms the value of the counter will be changed, as a result change detector will check the data in the template every 100ms (which adversely affects performance especially in big applications, since the change detection triggered in one component will trigger change detection in all components).</p><pre>setInterval( () =&gt; this.count++,100)</pre><p>setInterval, AddventListener, setTimeout, etc. are part of browser APIs (not part of the angular), therefore the question arises: how Angular understands that it is necessary to run change detector after the occurrence of the above mentioned events?. The answer is Zone.js!</p><h3>Zone.js</h3><p>Understanding how Angular keeps track of class properties and synchronous operations is pretty simple. The tricky part is asynchronous operations. The underlying idea of Zone.js is zone. The zone itself is the “<strong>execution context</strong>”, the place and state of the event. After the asynchronous operation is completed, the callback function is executed in the same zone where it was registered. So Angular finds out where the change occurred and what to check.</p><h4>Zone.js Monkey patch APIs</h4><p>By definition, the Monkey patch basically overrides the original API. In this way Zone.js overrides almost all native asynchronous functions and methods. Thus, it can track when the asynchronous function’s callback is executed. That is, the zone tells Angular when and where to start the change detection process.</p><pre>// this is the new version of addEventListener<br>function addEventListener(eventName, callback) {<br>     // call the real addEventListener<br>     callRealAddEventListener(eventName, function() {<br>        // first call the original callback<br>        callback(...);     <br>        // and then run Angular-specific functionality<br>        let changed = angular.runChangeDetection();<br>         if (changed) {<br>             angular.reRenderUIPart();<br>         }<br>     });<br>}</pre><p>Thanks to the zones, we know in which element the asynchronous event occurred. The remaining part is to understand whether changes need to be re-rendered for child elements, and there is a distinctive feature of Angular 2 here.<br> In the first Angular version, we had to run a digest cycle around the child and parent elements several times to check whether the model has changed or not. The second Angular checks for changes <strong>unidirectional</strong>.</p><h4>Disadvantages</h4><p>Zone.js changes the standard behavior of the browser API. Despite the fact that Monkey Patching is done neatly, there are additional costs in time when calling base functions. Although these costs are small, they are noticeable for big applications.</p><h3>NgZone run() and runOutsideOfAngular()</h3><p>From Angular official documentation : “<em>While Zone.js can monitor all the states of synchronous and asynchronous operations, Angular additionally provides a service called NgZone. This service creates a zone named </em><em>angular to automatically trigger change detection.”</em></p><h4>NgZone.run()</h4><p>Zone handles most asynchronous APIs such as setTimeout(), Promise.then(), and addEventListenner. Therefore you don’t need to trigger change detection for them manually.</p><p>There are still some third party APIs that Zone does not handle. In those cases, the NgZone service provides a run() method that allows you to execute a function inside the angular zone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b36dd1a40f503ba00d006a7143a0c617/href">https://medium.com/media/b36dd1a40f503ba00d006a7143a0c617/href</a></iframe><p>This function, and all asynchronous operations in that function, trigger change detection automatically at the correct time.</p><h4>runOutsideAngular</h4><p>Another common case is when you don’t want to trigger change detection. This is achieved by using another NgZone method: runOutsideAngular().</p><p>Suppose we have an animation in the application, i.e. simple &lt;div&gt; element that changes its background every 50 ms using a simple setInterval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd16a72b846cb98fa90407295246a362/href">https://medium.com/media/cd16a72b846cb98fa90407295246a362/href</a></iframe><p>Imagine what will happen if your application has 1000+ components. In all of them change detection will be triggered every 50ms, which will significantly affect the <strong>performance</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fenviousspryirrawaddydolphin&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fenviousspryirrawaddydolphin&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FEnviousSpryIrrawaddydolphin-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="450" height="368" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ca9a6c2362261a6c09b0cdb34cfe6f/href">https://medium.com/media/60ca9a6c2362261a6c09b0cdb34cfe6f/href</a></iframe><p>But, as you probably assume, there’s a simple way to fix it. You can just wrap it with NgZone.runOutsideAngular like this:</p><pre>ngOnInit(): void {<br>   this.ngZone.runOutsideAngular( _ =&gt; {<br>   this.changeColor()<br>   })<br>}</pre><p>Now we run timer outside NgZone and angular isn’t even “aware” that we fire these timers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fcorruptbreakabledeermouse&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fcorruptbreakabledeermouse&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FCorruptBreakableDeermouse-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="450" height="316" frameborder="0" scrolling="no"><a href="https://medium.com/media/696b9e25d8379d4105df9e1257739b35/href">https://medium.com/media/696b9e25d8379d4105df9e1257739b35/href</a></iframe><h3>Change Detection Strategies</h3><p>Angular has two variations of the change detection strategies:</p><ul><li>Default</li><li>OnPush</li></ul><p>The algorithm is set in the changeDetection property of the <a href="http://twitter.com/Component">@Component</a> () decorator configuration object and is specified for each component separately. If the parameter is not specified, the Default algorithm is used.</p><pre>@Component({<br>    selector: &#39;app-root&#39;,<br>    templateUrl: &#39;./app.component.html&#39;,<br>    styleUrls: [&#39;./app.component.scss&#39;], <br>    //changeDetection: ChangeDetectionStrategy.OnPush<br>})</pre><p>Default strategy checks every component in the component tree <strong>from top to the bottom</strong> every time an event triggers change detection. This is also called <strong>dirty checking </strong>and it will have negative impact on performance if your app consists of a big amount of components with a lot of asynchronous events like frequent calls to back-end, setIntervals, user events or even Socket connections.</p><p>Let’s take a look at the visualization of change detection Default strategy. Assume the initiator of change detection process in component tree is component “1” (a click event was fired).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Ftightsecondbufeo&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Ftightsecondbufeo&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FTightSecondBufeo-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="270" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/2037ead9da6e0ce6d3d886b283a70a6e/href">https://medium.com/media/2037ead9da6e0ce6d3d886b283a70a6e/href</a></iframe><h4>OnPush Change Detection Strategy</h4><p>OnPush change detection strategy provides the possibility to skip unnecessary checks for the component and all its child components. If we change the strategy for the component “A” to OnPush, and trigger change detection from component “1”, the change detection will not work for components “A”, “B” and “C”.</p><p>The next GIF demonstrates skipping parts of the component tree by using the OnPush change detection strategy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fmalespeedyladybird&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fmalespeedyladybird&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FMaleSpeedyLadybird-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="282" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/2758790664245c53169990b39446b650/href">https://medium.com/media/2758790664245c53169990b39446b650/href</a></iframe><p>You can test different variations on this example <a href="https://stackblitz.com/github/AregSargsyan/AngularChangeDetection/tree/master/CustomChangeDetection">here</a>.</p><p>When using the OnPush strategy, Angular will update component if:</p><ol><li><strong>The input reference has changed</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1dd15bbfb20d976abfa21c7cd3695a/href">https://medium.com/media/aa1dd15bbfb20d976abfa21c7cd3695a/href</a></iframe><p>After clicking on the button, we will not see any logs in the console. Angular simply compared the old and new values with a reference that remains the same.</p><pre>/** Returns false in our case */<br> if( oldValue !== newValue ) { <br>   runChangeDetection();<br> }</pre><p>As we know, numbers, booleans, strings, null and undefined are primitive types. All primitive types are passed by value. Objects, arrays, and functions are passed by reference.To start the change detection mechanism, we must change the object reference itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beaa30f3211f6a1f055ae45fc2e0d8d5/href">https://medium.com/media/beaa30f3211f6a1f055ae45fc2e0d8d5/href</a></iframe><p><strong>2 . An event inside a component or its descendants</strong></p><p>The component has an internal state, which is updated when an event occurs from the component itself or its descendants.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18c1c1fbadf85266db205d64b761ab3c/href">https://medium.com/media/18c1c1fbadf85266db205d64b761ab3c/href</a></iframe><p>When we click on the button, Angular starts the change detection cycle and the view is updated as expected.</p><p>Perhaps you think that all asynchronous operations should trigger the change detection mechanism, as mentioned at the beginning. But for OnPush strategy the rule applies <strong>only to DOM events.</strong></p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8697c649533c837f4bc575e741657ce/href">https://medium.com/media/b8697c649533c837f4bc575e741657ce/href</a></iframe><p>Note that the count property has changed, but there will be no changes in the HTML, we should run change detection manually.</p><p><strong>3. Change detection is triggered manually</strong></p><p>Angular provides three methods for manually launching the mechanism for detecting changes.</p><ul><li><strong><em>detectChanges() </em></strong>tells Angular to start detecting changes in the component and its descendants(if they have default strategy). Previous example can be rewritten as follows (now change detection will be triggered)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fc7bca2f14fccab853c94753c83b6b/href">https://medium.com/media/79fc7bca2f14fccab853c94753c83b6b/href</a></iframe><ul><li><strong>ApplicationRef.tick() </strong>same as zone.run() cause change detection on the whole application(exceptions are the branches of tree with OnPush strategy)</li><li><strong>markForCheck() </strong>does not trigger change detection. Instead, it marks the component and all its parents (no matter what their strategy is set) that they should be checked in the current or next change detection cycle.</li></ul><p><strong>5. Async Pipe</strong></p><p>Async pipe subscribes to the observed object or promise and returns the last value given to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10b707ecdc8ff9cfa71edc75314de669/href">https://medium.com/media/10b707ecdc8ff9cfa71edc75314de669/href</a></iframe><p>Internally the AsyncPipe calls markForCheck() each time a new value is emitted</p><h3>Conclusion</h3><p>In most cases, especially if your application does not exceed 100 components, Angular’s change detection default strategy works pretty fast. But in large applications, especially if your goal is performance, you need to do this work by yourself and develop a change detection algorithm suitable for your particular case. Anyways it is important to know how Angular works under the hood in order to avoid or fix various errors.</p><p>You can practice different variations of change detection in example described in this article <a href="https://stackblitz.com/github/AregSargsyan/AngularChangeDetection/tree/master/CustomChangeDetection">here</a>.</p><p>As always feel free to contact me on <a href="https://www.linkedin.com/in/areg-sargsyan-341b4a193">LinkedIn</a> in case of questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5103fab3866" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/angular-change-detection-ngzone-a5103fab3866">How to improve performance of Angular application with Change Detection and NgZone</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular: Easy to understand]]></title>
            <link>https://medium.com/@Areg_Sargsyan/rxjs-in-angular-6526bcff0d74?source=rss-a227d815bfe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6526bcff0d74</guid>
            <category><![CDATA[subject]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular-9]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[rxjs-watcher]]></category>
            <dc:creator><![CDATA[Areg Sargsyan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 06:36:19 GMT</pubDate>
            <atom:updated>2021-10-01T13:37:15.112Z</atom:updated>
            <content:encoded><![CDATA[<h3>RxJS in Angular:Easy to understand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*uqBah-AUTg9MDdgJDztb2w.png" /></figure><p>Many experienced Front-end developers avoid using RxJS library and still use good and old promises instead. The main reason is misunderstanding of asynchronous processes and fear of RxJS, especially of its huge amount of operators. But these operators will help us more than confuse as we begin writing flexible and good looking code. I think when you start using RxJS, you will fall in love with its comfort and ease of use. This will become one of your favorite libraries.</p><h3><strong>What is reactive programming?</strong></h3><p>Reactive programming is about asynchronous data streams and data changes propagation in streams.</p><p>There are several characteristics of reactive programming:</p><p>- oriented on interaction with asynchronous data streams</p><p>- streams have the ability to transfer other streams</p><p>- data transmitted over the stream are listened by subscribers</p><p>- subscribers respond to data changes</p><h3>RxJS library</h3><p>RxJS implements the reactive programming paradigm in JavaScript. It is included in the Angular framework as an integral part. Some built-in Angular classes (HttpClient, Router.events, FormControl) are inherited from the Observable class.</p><h3>Observable</h3><p>In simple words we can say:</p><p>Observable — means an object that can be observed, they are lazy collections of multiple values over time, or Observables are the ones who emit some values.</p><p>Observers are the one who catch those values. An observer subscribes to an observable in order to receive and react to the events emitted by the observable.</p><p>If you come from the world of promises the key difference is that unlike observables promises always return only one value.</p><p>Another difference is that observables are cancelable whereas promises are not. If you need to you can unsubscribe from observable. In the case of promises the process producing the resolution of current promise is already underway, and you generally don’t have access to prevent the execution.</p><p>RxJS library — consists mainly of methods for working with streams.</p><p>You can create a stream from the Observable class using the constructor (new) or through the Observable.create method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*lkse8AJM2lJmf4oMGA4y6g.png" /></figure><p>The observable can emit the following event:</p><ul><li>“next”: Event is used to emit the next value from the Observable.</li><li>“error”: Following event is used to notify Observer about some error.</li><li>“complete”: Notifies that Observable has completed emitting data.</li></ul><p>Without a subscription, a stream will not be executed, so the RxJS library optimizes stream creation. Subscription to a stream is made using the subscribe () method.The subscribe () method accepts three callback functions: next (), error (), complete () and returns a Subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*LIkkponsfBYf2WHu4Fs12w.png" /></figure><p>To practice a Basic Angular Observable and RxJS let’s create an Observable which emits a Random value after each second.</p><p>This will be a simple Observable containing a single event “next”</p><pre>randomNumberGenerator = Observable.create((observer) =&gt; {<br>    for (let i = 0; i &lt; 10; i++) {</pre><pre>setTimeout(() =&gt;  observer.next(Math.floor(Math.random() * 100)), 1000 * i)<br>    }<br>});</pre><p>Now since we have a sample Observable available, we can create a simple subscriber which subscribes to the Observable. Below is the code of subscribing to the Observable (Example 1).</p><pre>ngOnInit(): void {</pre><pre>this.randomNumberGenerator.subscribe((value)=&gt; console.log(value))</pre><pre>}</pre><p>The subscribe function takes a callback as an argument to respond to different events that are emitted from Observers.In the case described above the argument will handle “next” event by default.</p><p>The data emitted from Observable is captured by the specified function in “value” parameter which is later displayed in the console.</p><h3>Interaction with streams. Pipeable operators</h3><p>RxJs provides a method called “pipe” to interact with streams. As an arguments this method takes so-called pipeable operators.</p><p>Pipeable operators are the functions that take streams as arguments manipulate the value of these streams and return this manipulated data.</p><pre>import {/* ops… */} from &#39;rxjs/operators&#39;;</pre><pre>observable</pre><pre>.pipe(/*</pre><pre>op1(),</pre><pre>op2()</pre><pre>...</pre><pre>*/</pre><p>The example 1 can be changed as follows (Example 2):</p><pre>this.randomNumberGenerator.pipe(filter((val:number) =&gt; val % 2 === 0)).subscribe((value) =&gt; console.log(value))</pre><p>In the example 2 we can see that only even numbers will be emitted.</p><p>You can reed about all pipeable operators <a href="https://rxjs-dev.firebaseapp.com/guide/operators">here</a>.</p><h3>Subject</h3><p>There are two types of Observables:</p><ul><li>Cold — creates a new independent stream for each subscription.</li></ul><p>As a rule, all created Observable are cold.</p><ul><li>Hot — doesn’t create a new stream for each subscription. All subscribers receive same generated values.</li></ul><p>In practice you often come up with situations where you need to obtain a shared (Hot) data stream from one cold Observable. For example, HttpClient.get() returns a cold Observable, which means that several subscriptions will send different get() requests. Subject will help us handle this situation.</p><p>Subject is another way to create a stream in the RxJS library. They are created using the new Subject () constructor:</p><pre>const source$ = new Subject()</pre><p>Subject allows you to add data to the stream at any time with the .next () construct:</p><pre>source$.next(&#39;first value&#39;);</pre><pre>source$.next(&#39;second value&#39;);</pre><pre>// ...</pre><h3>BehaviorSubject</h3><p>BehaviorSubject is a class that inherits the methods and properties of the Subject class but allows you to set the initialization value in the constructor function.</p><pre>const source$ = new BehaviorSubject(&#39;init value’);</pre><h3>ReplaySubject</h3><p>ReplaySubject is a class that inherits the methods and properties of the Subject class and saves stream values to the buffer. The size of the buffer is set in the constructor. The new subscription will immediately receive the contents of the buffer.</p><pre>const source$ = new ReplaySubject(2);</pre><h3>AsyncSubject (rarely used)</h3><p>AsyncSubject is a class that inherits the methods and properties of the Subject class which passes the last value of the stream to the subscribers only after streams completion.</p><pre>const source$ = new AsyncSubject();</pre><h3>RxJS Watcher</h3><p>RxJS Watcher is a Google Chrome and FireFox extension that can be used to visualize Observables. I recommend to use it in order to understand reactive programming better.</p><h4>Installation</h4><p>Install npm package</p><pre>npm i rxjs-watcher --save-dev</pre><p>Next you will need to install extension for Chrome or FireFox.</p><p>To use it we should add ‘watch’ operator from rxjs-watcher package. It take 2 arguments: first is label of the stream which has type of string and the second is duration given in seconds.</p><p>Now begins the most interesting!</p><p>Let’s slightly change the code given in Example 1.</p><pre>this.randomNumberGenerator.pipe(<em>watch(&quot;Interval (2000)&quot;, 20)</em>).subscribe((value) =&gt; console.log(value))</pre><p>Now we can see the whole process in the extension and emitted values — by clicking on the marbles.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM9eap4KPApg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM9eap4KPApg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM9eap4KPApg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d986dbdcb0495ccbb6e4d0fec6b452b9/href">https://medium.com/media/d986dbdcb0495ccbb6e4d0fec6b452b9/href</a></iframe><p>We can also modify the code above so that the observable will complete after 5.5 seconds.</p><pre>setTimeout(()=&gt; observer.complete(), 5500)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKE9KDTn2qt4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKE9KDTn2qt4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKE9KDTn2qt4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/092d0dda9c15daa4ed62e7181d5f9ec3/href">https://medium.com/media/092d0dda9c15daa4ed62e7181d5f9ec3/href</a></iframe><p>This is a very simple example but in real projects there will be situations when it is difficult to debug and see why the stream has stopped or where the error has occurred. This extension will come in handy in situations like this.</p><p>Cool? I think Yes!</p><p>Now you can try different operations with observeables, using the operators from RxJS documentation and visually follow the process.</p><h3>RxJS and Angular</h3><p>Some built-in Angular classes inherit methods from the Observable class:</p><ul><li>EventEmitter — inherits Observable and extends it by adding the emit () method</li><li>HttpClient — returns instances of the Observable class from HTTP methods</li><li>Async pipe — automatically subscribes to Observable instances and displays the result of the asynchronous operation in the component</li><li>Router.events — returns routing events as an instance of Observable</li><li>ActivateRoute.url — returns events of URL parameters as an instance of Observable</li><li>Reactive forms FormControl — contains valueChanges and statusChanges methods that return Observable instances.</li></ul><p>Angular built-in classes can automatically manage memory and terminate all streams created in the component life cycle. It is necessary to unsubscribe from all custom created streams in the component using the unsubscribe () method so as to avoid memory and performance issues.</p><p>The best place to unsubscribe is the ngOnDestroy component lifecycle hook. It is considered to be a best practice to keep subscription in component level variable that is accessible from all methods.</p><pre>@Component({…})</pre><pre>export class AppComponent implements OnInit, OnDestroy {</pre><pre>subscription: Subscription;</pre><pre>ngOnInit() {</pre><pre>this.subscription = interval(500).subscribe(x =&gt; console.log(x));</pre><pre>}</pre><pre>ngOnDestroy() {</pre><pre>this.subscription.unsubscribe();</pre><pre>}<br>}</pre><p>But what if you have multiple streams? Do you really need to have multiple component level variables and unsubscribe from them sequentially? If you are using less abstractions to get the job done this approach will work and will have a slight privilege in performance but will not be considered as clean code. A better solution is to have a single parent subscription and add other as children so that in ngOnDestroy you can unsubscribe only from parent. But the best practice is to use RxJS operators to kill a stream:</p><ul><li>take(n): stop the observable after emitting n values</li><li>takeWhile(predicate): if predicate returns false observable will complete</li><li>first(): emits the first value and completes.</li><li>takeUntil(notifier: Observable): emit values until provided observable emits</li></ul><p>We can modify the previous example by adding pipeable operator take() and deleting ngOnDestroy method</p><pre>this.subscription = interval(500).pipe(take(5)).subscribe(x =&gt; console.log(x));</pre><p>The first noticeable change is the decrement of code amount. But the main benefit of this approach is that we are not calling unsubscribe() method explicitly.</p><h3>mergeMap</h3><p>Since HTTP methods return an instance of Observable class it is convenient to work with them using RxJS methods.</p><p>There are cases when we need to get data from the backend and based on the data received, make another HTTP request. To avoid nested subscribe() calls the mergeMap() method may come in handy.</p><pre>@Component({…})</pre><pre>export class AppComponent {</pre><pre>user$: Observable&lt;{}&gt;;</pre><pre>constructor(private http: HttpClient) { }</pre><pre>ngOnInit() {</pre><pre>this.user$ = this.http.get(&quot;someURL&quot;).pipe(</pre><pre>mergeMap(user =&gt; this.http.get(&quot;anotherURL/&quot;+user.id))</pre><pre>);</pre><pre>this.user$.subscribe(data =&gt; console.log(data));</pre><pre>}</pre><pre>}</pre><p>Let’s understand together the difference between 2 combination operators’ work principle that are often used in practice.</p><h3>ForkJoin and Zip</h3><p>These RxJS operators are useful for making parallel HTTP requests and combining their results. Both take ‘n’ number streams collect values form all of them and return the result as an array.</p><p>Assume we have two different observable randomNumberGenerator described previously. Now let’s combine them using two combination operators and use RxJS Watcher for visualization.</p><pre>forkJoin([this.randomNumberGenerator1,this.randomNumberGenerator2 ]).pipe(watch(&quot;forkjoin&quot;, 8)).subscribe(console.log)</pre><pre>zip(this.randomNumberGenerator1,this.randomNumberGenerator2 ).pipe(watch(&quot;zip&quot;, 8)).subscribe(console.log)</pre><p>You can easily understand the difference between ForkJoin and Zip from the video below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRuhWP1oPemM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRuhWP1oPemM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRuhWP1oPemM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a18d83238e1593c32febee235570a3/href">https://medium.com/media/c3a18d83238e1593c32febee235570a3/href</a></iframe><p>ForkJoin waits for all internal streams to complete, packs their last values and emits the result only once. If one of the internal streams fails to complete, then ForkJoin will not emit any value.</p><p>Zip emits the result each time it receives the value from each of the internal streams.</p><p>In Angular apps the are cases when it is necessary to send several HTTP requests parallel and wait for responses from all of them so as to work with combined response data. This behavior may resemble the static Promise.all() method.</p><p>ForkJoin is the easiest way to achieve this.</p><pre>forkJoin([</pre><pre>this.http.get(this.requestUrl1),</pre><pre>this.http.get(this.requestUrl2),</pre><pre>this.http.get(this.requestUrl3),</pre><pre>this.http.get(this.requestUrl4),</pre><pre>this.http.get(this.requestUrl5)]).subscribe(responeArray =&gt; &#39;do something with responseArray&#39;)</pre><h3>Conclusion</h3><p>You can read about RxJS operators <a href="https://rxjs-dev.firebaseapp.com/guide/operators">here</a> and <a href="https://www.learnrxjs.io/learn-rxjs/operators">here</a>.</p><p>Yeah, you will see more than 80 operators with corresponding descriptions, probably you will be scared, but believe me you are not the only one :) Do not rush to leave! Several questions may come to you e.g : “Which operator should I use?”, “Which one will be the perfect suite for my case?” etc. Usually the result of different operators might be the same (that’s why people get confused). It is better to understand the purpose and the underlying logic of the operator in order to make an appropriate decision. All you need to do is read the documentation and to practice operator by operator. Remember practice is everything!</p><p>Thank you for reading, if you have any questions feel free to ask me <a href="https://www.linkedin.com/in/areg-sargsyan-341b4a193">here </a>, I will be happy to help!</p><p>I am the owner of the development company <a href="https://upandrun.io/">Up&amp;Run</a> and our goal is to shed light on any of Your questions and problems. For free consultation ping <a href="/service/mailto:contact@upandrun.io">contact@upandrun.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6526bcff0d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>