<?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 Rahul Pengoria on Medium]]></title>
        <description><![CDATA[Stories by Rahul Pengoria on Medium]]></description>
        <link>https://medium.com/@rahulpengoria.r3h?source=rss-8872926be5bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KB4MCOx94j2h8FzZ</url>
            <title>Stories by Rahul Pengoria on Medium</title>
            <link>https://medium.com/@rahulpengoria.r3h?source=rss-8872926be5bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:22:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulpengoria.r3h/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[Understanding RunLoop in iOS: A Brief Guide]]></title>
            <link>https://medium.com/@rahulpengoria.r3h/understanding-runloop-in-ios-a-brief-guide-c10c352c2a29?source=rss-8872926be5bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10c352c2a29</guid>
            <dc:creator><![CDATA[Rahul Pengoria]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 20:00:04 GMT</pubDate>
            <atom:updated>2025-03-15T20:17:53.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-qO5XJ1i7ftouFWZKhuIw.jpeg" /></figure><h3>Introduction</h3><p>In iOS, a <strong>RunLoop</strong> is an essential part of event-driven programming. It ensures that a thread remains active while efficiently handling tasks such as user interactions, timers, and network requests. The main thread of an iOS app has a built-in RunLoop, which processes UI events, while background threads need a manually managed RunLoop if they need to stay alive.</p><h3><strong>What is a RunLoop?</strong></h3><p>A <strong>RunLoop</strong> is an event-processing loop that continuously waits for input sources (such as touch events, timers, and network responses) and processes them in an efficient manner. It prevents threads from exiting immediately and helps in managing asynchronous tasks.</p><h4>RunLoop: The Chill Manager of Your Thread</h4><p>RunLoop is like that one lazy friend who just lounges around doing nothing — until there’s actual work to do. It’s an <strong>infinite loop</strong> that just <strong>chills</strong> when nothing is happening, but the moment a task (event) arrives, it <strong>springs into action</strong> like a pro. Think of it as a <strong>thread’s personal manager</strong>, deciding <strong>what gets executed and when</strong>, making sure your app runs smoothly without wasting energy.</p><blockquote><strong>RunLoop ensures that a thread does not remain idle without reason and continues handling events efficiently.</strong></blockquote><p><strong>Let’s understand with example:</strong></p><blockquote>🚉 <strong>RunLoop vs Railway Station: A Fun Analogy</strong></blockquote><blockquote>Imagine a railway station where a Ticket Checker (TT) is on duty.</blockquote><blockquote>🚉 No Train (No Event): The TT is relaxing, sipping tea ☕, waiting for work.</blockquote><blockquote>🚆 Train Arrives (Event Occurs): The TT springs into action, checks tickets, and processes passengers.</blockquote><blockquote>✅ Work Done (No Pending Events): The TT goes back to chill mode until the next train arrives.</blockquote><blockquote>Just like the <strong>TT efficiently manages trains</strong>, a <strong>RunLoop keeps a thread alive — executing tasks when needed and resting when idle. No unnecessary stress, just smooth operations! </strong>😆</blockquote><p><strong>Still Didn’t Understand? Let’s Take One More Example!</strong></p><blockquote>👉 <strong>RunLoop as a Restaurant Waiter: A Fun Analogy</strong></blockquote><blockquote>Think of <strong>RunLoop</strong> as a <strong>waiter in a restaurant</strong>.</blockquote><blockquote>🍽️ <strong>No Customers Ordering (No Event):</strong> The waiter is just <strong>chilling</strong>, waiting for someone to call.</blockquote><blockquote>📝 <strong>Order Arrives (Event Occurs):</strong> The waiter <strong>springs into action</strong>, takes the order, and ensures it gets processed.</blockquote><blockquote>⏳ <strong>Waiting for the Next Order:</strong> Once the food is served, the waiter <strong>goes back to wait mode</strong> until another customer signals.</blockquote><blockquote>Just like a <strong>waiter efficiently manages orders</strong>, a <strong>RunLoop keeps a thread alive — handling tasks only when needed and conserving energy otherwise</strong>. <strong>No unnecessary rush, just smooth service!</strong> 😆</blockquote><p>💡 <strong>Moral of the Story:</strong> A <strong>RunLoop</strong> manages a thread’s life cycle and ensures that <strong>CPU power is not wasted</strong>. It keeps the thread <strong>efficient</strong>, handling tasks when needed and resting when idle — just like a smart worker who knows when to hustle and when to chill! 😆🚀</p><h4>Key Responsibilities of RunLoop:</h4><ul><li>Keeps a thread alive while waiting for events.</li><li>Processes input sources like UI events, network responses, and timers.</li><li>Puts the thread to sleep when idle to conserve system resources.</li></ul><h3>🎯 Types of Tasks in RunLoop</h3><p>A <strong>RunLoop</strong> handles events from different sources, ensuring smooth execution of tasks. These sources can be categorized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*RTtWV-R8-qJ-OuFdgZgqXg.png" /></figure><h4>🔍 Explanation</h4><ul><li><strong>Input Sources</strong>: Handles <strong>asynchronous events</strong> like user interactions or network responses.</li><li><strong>Timer Sources</strong>: Executes code <strong>at specific intervals</strong>, like updating a countdown timer.</li><li><strong>Observer Sources</strong>: Listens for system events, such as <strong>UI layout changes</strong> or app lifecycle events.</li></ul><p>💡 <strong>Moral:</strong> RunLoop efficiently manages multiple event types, ensuring your app remains <strong>responsive and efficient!</strong> 🚀</p><h3>RunLoop in iOS</h3><h4><strong>1. RunLoop.main vs RunLoop.current</strong></h4><p>A <strong>RunLoop is always associated with a thread</strong>, but by default, it <strong>only exists on the main thread</strong>. For other threads, you need to <strong>manually create and start</strong> a RunLoop.</p><h4>What is RunLoop.main?</h4><p><strong>RunLoop.main</strong> is simply a <strong>reference to the RunLoop of the main thread</strong>.</p><h4>Why is RunLoop.main Important?</h4><p>✅ <strong>UI-related tasks must always run on the main thread</strong>, which is why <strong>RunLoop.main </strong>is responsible for handling UI updates.<br> ❌ If you try to update the UI from a background thread, your app can <strong>crash</strong> or show unexpected behavior.</p><p>Let’s say we have a <strong>timer</strong> that needs to update the UI every second. Since UI updates must run on the <strong>main thread</strong>, we use <strong>RunLoop.main</strong>.</p><pre>class TimerExample {<br>    var timer: Timer?<br><br>    func startTimer() {<br>        timer = Timer(timeInterval: 1.0, repeats: true) { _ in<br>            print(&quot;Timer fired! Updating UI on main thread.&quot;)<br>        }<br>        <br>        // Add timer to the main RunLoop<br>        RunLoop.main.add(timer!, forMode: .common)<br>    }<br><br>    func stopTimer() {<br>        timer?.invalidate()<br>        timer = nil<br>    }<br>}</pre><h4>RunLoop Creation Process:</h4><ol><li>When a <strong>thread starts</strong>, the system <strong>does NOT automatically create a RunLoop</strong> for it.</li><li>If you want to use a <strong>RunLoop inside a thread</strong>, you must call <strong>RunLoop.current</strong>.</li><li>To keep the RunLoop <strong>continuously running</strong>, you must call <strong>run()</strong>.</li></ol><p><strong><em>Example: Creating a RunLoop in a Background Thread</em></strong></p><pre>class BackgroundTask {<br>    func start() {<br>        let thread = Thread {<br>            let runLoop = RunLoop.current  // 1. Get current thread&#39;s RunLoop<br>            runLoop.add(NSMachPort(), forMode: .default) // 2. Add a source<br>            runLoop.run() // 3. Start the RunLoop<br>        }<br>        thread.start()<br>    }<br>}</pre><h4>2. RunLoop Modes</h4><p>RunLoop operates in different <strong>modes</strong>, each managing specific types of input sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*3F8pXh-cbIglVaM0hNXVVg.png" /></figure><p><strong><em>Example:</em></strong></p><pre>RunLoop.current.run(mode: .default, before: .distantFuture)</pre><h4>When Do You Need to Use a RunLoop?</h4><ol><li>Handling background tasks that need to stay alive (e.g., networking, Bluetooth, inter-thread communication).</li><li>Using Timer in a background thread (as Timer needs a RunLoop to function).</li><li>Listening for external events (e.g., sockets, file system changes).</li><li>Not needed for standard DispatchQueue background tasks, as they exit after execution.</li></ol><h3>Conclusion</h3><p>A <strong>RunLoop</strong> is crucial for managing asynchronous events in iOS apps. It ensures that the main thread stays responsive and allows background threads to process events efficiently. While the main thread’s RunLoop is managed by the system, background threads require explicit handling to stay alive. Understanding RunLoop is essential for building performant and responsive iOS applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10c352c2a29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>