<?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 Roopesh Tripathi on Medium]]></title>
        <description><![CDATA[Stories by Roopesh Tripathi on Medium]]></description>
        <link>https://medium.com/@scripturesintech?source=rss-b8781e45b90c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y9SxMuO2kBOx5Azzf6QTCg.png</url>
            <title>Stories by Roopesh Tripathi on Medium</title>
            <link>https://medium.com/@scripturesintech?source=rss-b8781e45b90c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:46:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scripturesintech/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[ Token Expiry Handling Flutter/Dart— Generic Architecture]]></title>
            <link>https://scripturesintech.medium.com/token-expiry-handling-flutter-dart-generic-architecture-c378fc41bdb4?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c378fc41bdb4</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-dio]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 06:09:10 GMT</pubDate>
            <atom:updated>2025-12-21T06:09:10.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SghKpyHNbqtPPaZp_blPWQ.png" /></figure><h3>🎯 Problem to Solve</h3><ul><li>Access token expires frequently (minutes)</li><li>Refresh token expires less frequently (longer)</li><li>App must:</li><li>Refresh silently when possible</li><li>Force logout when session truly ends</li><li>Avoid UI confusion, retries, and loops</li></ul><h3>🧠 Core Principles (Non-Negotiable)</h3><ol><li><strong>Access token expiry is recoverable</strong></li><li><strong>Refresh token expiry is NOT recoverable</strong></li><li><strong>Client reacts only to server signals</strong></li><li><strong>Backend owns all expiry decisions</strong></li></ol><h3>🪪 Token Types</h3><pre>Access Token<br>- Short lived (e.g. 5 minutes)<br>- Sent with every API call<br><br>Refresh Token<br>- Longer lived (e.g. 20 minutes)<br>- Used only to get new access token</pre><h3>🔁 High-Level Flow (Text Diagram)</h3><pre>API Request<br>  ↓<br>Attach Access Token<br>  ↓<br>Server validates token<br>  ↓<br>┌───────────────┬───────────────────────┐<br>│ Token valid   │ Token expired         │<br>│ (200 OK)      │ (401 Unauthorized)    │<br>│               │                       │<br>│ Continue UI   │ Trigger refresh flow  │<br>└───────────────┴───────────────────────┘</pre><h3>✅ Case 1: Access Token Expired (Recoverable)</h3><h3>Backend behavior</h3><pre>Access token expired<br>→ Respond with HTTP 401</pre><h3>Client behavior (generic)</h3><pre>onApiError(error):<br>  if error.statusCode == 401:<br>    if refreshInProgress:<br>      queueRequest()<br>      return<br><br>refreshInProgress = true<br>    if refreshToken is missing:<br>      handleSessionExpired()<br>      return<br>    success = callRefreshTokenApi()<br>    refreshInProgress = false<br>    if success:<br>      retryOriginalRequest()<br>      retryQueuedRequests()<br>    else:<br>      handleSessionExpired()</pre><h3>Result</h3><p>✔ User stays logged in<br> ✔ No UI interruption<br> ✔ Seamless recovery</p><h3>❌ Case 2: Refresh Token Expired (NOT Recoverable)</h3><h3>Backend behavior</h3><pre>Refresh token expired<br>→ Refresh API returns 401</pre><h3>Client behavior</h3><pre>callRefreshTokenApi():<br>  response = refreshApiCall()<br><br>if response.success:<br>    saveNewTokens()<br>    return true<br>  else:<br>    return false</pre><p>Then:</p><pre>handleSessionExpired():<br>  clearAllTokens()<br>  resetNavigation()<br>  showSessionExpiredMessage()</pre><h3>🚪 Session Expired — UI Handling (Critical)</h3><h3>UX Rules</h3><ul><li>User <strong>must understand what happened</strong></li><li>Message must <strong>not disappear</strong></li><li>User must <strong>acknowledge</strong></li></ul><h3>Recommended UI</h3><pre>Alert Dialog<br>----------------------------<br>Session Expired<br><br><br>Your session has expired.<br>Please log in again.<br>[ OK ]<br>----------------------------</pre><h3>Why not Snackbar?</h3><p>❌ Auto-dismiss<br> ❌ User may miss it<br> ❌ Not suitable for forced actions</p><h3>🧱 Separation of Responsibilities (Best Practice)</h3><h3>Backend</h3><ul><li>Validates tokens</li><li>Decides expiry</li><li>Returns correct HTTP codes</li><li>Rotates refresh tokens (optional)</li><li>Enforces absolute session expiry</li></ul><h3>Client</h3><ul><li>Attaches access token</li><li>Reacts to 401</li><li>Calls refresh API</li><li>Handles UI logout</li></ul><h3>🔄 Refresh Token Rotation (Generic)</h3><pre>refreshApi(refreshToken):<br>  if refreshToken valid AND session not expired:<br>    invalidate old refresh token<br>    issue new access token<br>    issue new refresh token<br>  else:<br>    reject request</pre><p>⚠ Rotation does <strong>NOT</strong> mean infinite session<br> Backend still enforces <strong>hard session expiry</strong></p><h3>🧨 Edge Cases (Handled by Design)</h3><p>ScenarioResultMultiple APIs fail at same timeQueued, refreshed onceRefresh failsSingle logoutRefresh token stolenRotation detects reuseApp in backgroundNext API triggers refreshUser idle too longForced logout</p><h3>🔥 Interview-Ready Summary</h3><blockquote><em>Access token expiry is handled silently by refreshing the token when the server returns a 401. Refresh token expiry indicates the session has ended, so the client clears authentication state and forces the user to log in again with a clear UI message.</em></blockquote><h3>✅ Mental Model</h3><pre>401 from API        → Try refresh<br>Refresh succeeds   → Retry request<br>Refresh fails      → Session expired<br>Session expired    → Logout + Alert</pre><h3>🎯 <strong><em>Token Expiry in Flutter using Dio</em></strong></h3><p>we’ll design a <strong>clean, scalable, and secure</strong> solution for handling:</p><ul><li>✅ Access token expiry</li><li>❌ Refresh token expiry</li><li>🔁 Parallel API calls</li><li>🧭 Proper UI handling</li></ul><h3>🧠 Core Concepts (Before Code)</h3><h3>Token Types</h3><p><strong>Access Token</strong></p><ul><li>Short-lived (e.g. 5 minutes)</li><li>Sent with every API request</li></ul><p><strong>Refresh Token</strong></p><ul><li>Longer-lived (e.g. 20 minutes)</li><li>Used only to obtain new access tokens</li></ul><h3>🔁 High-Level Flow</h3><pre>API Request<br>  ↓<br>Attach Access Token<br>  ↓<br>Server validates token<br>  ↓<br>401 Unauthorized?<br>  ↓<br>Refresh token<br>  ↓<br>Retry original request</pre><h3>🧱 Architecture Overview</h3><pre>┌──────────────┐<br>│ UI / Screens │<br>└───────▲──────┘<br>        │<br>┌───────┴────────┐<br>│ AuthInterceptor│  ← Token logic<br>└───────▲────────┘<br>        │<br>┌───────┴────────┐<br>│ TokenRepository│<br>└────────────────┘</pre><h3>🧩 Flutter + Dio Implementation</h3><h3>1️⃣ Token Repository (Abstraction)</h3><pre>abstract class TokenRepository {<br>  Future&lt;String?&gt; getAccessToken();<br>  Future&lt;String?&gt; getRefreshToken();<br><br>Future&lt;void&gt; saveTokens(String accessToken, String refreshToken);<br>  Future&lt;void&gt; clearTokens();<br>}</pre><h3>2️⃣ AuthInterceptor (Core Logic)</h3><pre>class AuthInterceptor extends Interceptor {<br>  final Dio dio;<br>  final TokenRepository repo;<br><br>bool _isRefreshing = false;<br>  final List&lt;Future&lt;void&gt; Function()&gt; _retryQueue = [];<br>  AuthInterceptor(this.dio, this.repo);<br>  @override<br>  void onRequest(<br>    RequestOptions options,<br>    RequestInterceptorHandler handler,<br>  ) async {<br>    if (_isAuthFreePath(options.path)) {<br>      return handler.next(options);<br>    }<br>    final token = await repo.getAccessToken();<br>    if (token != null) {<br>      options.headers[&#39;Authorization&#39;] = &#39;Bearer $token&#39;;<br>    }<br>    handler.next(options);<br>  }<br>  @override<br>  void onError(<br>    DioException err,<br>    ErrorInterceptorHandler handler,<br>  ) async {<br>    if (err.response?.statusCode == 401 &amp;&amp;<br>        !_isAuthFreePath(err.requestOptions.path)) {<br>      if (_isRefreshing) {<br>        _retryQueue.add(() async {<br>          final response = await _retry(err.requestOptions);<br>          handler.resolve(response);<br>        });<br>        return;<br>      }<br>      _isRefreshing = true;<br>      try {<br>        final refreshToken = await repo.getRefreshToken();<br>        if (refreshToken == null) {<br>          await _forceLogout();<br>          handler.reject(err);<br>          return;<br>        }<br>        final success = await _refreshToken(refreshToken);<br>        if (!success) {<br>          await _forceLogout();<br>          handler.reject(err);<br>          return;<br>        }<br>        final response = await _retry(err.requestOptions);<br>        handler.resolve(response);<br>        for (final retry in _retryQueue) {<br>          await retry();<br>        }<br>        _retryQueue.clear();<br>      } finally {<br>        _isRefreshing = false;<br>      }<br>      return;<br>    }<br>    handler.next(err);<br>  }<br>  bool _isAuthFreePath(String path) {<br>    return path.contains(&#39;/login&#39;) || path.contains(&#39;/refresh&#39;);<br>  }<br>  Future&lt;Response&gt; _retry(RequestOptions request) async {<br>    final newToken = await repo.getAccessToken();<br>    return dio.request(<br>      request.path,<br>      data: request.data,<br>      queryParameters: request.queryParameters,<br>      options: Options(<br>        method: request.method,<br>        headers: {<br>          ...request.headers,<br>          &#39;Authorization&#39;: &#39;Bearer $newToken&#39;,<br>        },<br>      ),<br>    );<br>  }<br>  Future&lt;bool&gt; _refreshToken(String refreshToken) async {<br>    try {<br>      final refreshDio = Dio();<br>      final response = await refreshDio.post(<br>        &#39;/api/token/refresh&#39;,<br>        data: {&#39;refresh_token&#39;: refreshToken},<br>      );<br>      await repo.saveTokens(<br>        response.data[&#39;access_token&#39;],<br>        response.data[&#39;refresh_token&#39;],<br>      );<br>      return true;<br>    } catch (_) {<br>      return false;<br>    }<br>  }<br>  Future&lt;void&gt; _forceLogout() async {<br>    _retryQueue.clear();<br>    await repo.clearTokens();<br>    // UI navigation handled centrally<br>    AuthSession.instance.notifyExpired();<br>  }<br>}</pre><h3>🚪 Refresh Token Expired → UI Handling</h3><h3>❌ Why Snackbar is Wrong</h3><ul><li>Auto-dismiss</li><li>User misses message</li><li>Forced logout needs acknowledgment</li></ul><h3>✅ Correct UX: Blocking Alert</h3><pre>void handleSessionExpired(BuildContext context) {<br>  showDialog(<br>    context: context,<br>    barrierDismissible: false,<br>    builder: (_) =&gt; AlertDialog(<br>      title: const Text(&#39;Session Expired&#39;),<br>      content: const Text(<br>        &#39;Your session has expired. Please log in again.&#39;,<br>      ),<br>      actions: [<br>        TextButton(<br>          onPressed: () {<br>            Navigator.of(context).pushAndRemoveUntil(<br>              MaterialPageRoute(builder: (_) =&gt; LoginScreen()),<br>              (_) =&gt; false,<br>            );<br>          },<br>          child: const Text(&#39;OK&#39;),<br>        ),<br>      ],<br>    ),<br>  );<br>}</pre><h3>🔄 Refresh Token Rotation (Important Note)</h3><p>Even if the backend <strong>rotates refresh tokens</strong>, it should still enforce:</p><ul><li>Absolute session expiry</li><li>Logout after maximum lifetime</li></ul><p>Rotation ≠ infinite session.</p><h3>🔥 Common Edge Cases (Handled)</h3><p>✔ Multiple API calls fail → queued<br> ✔ One refresh request only<br> ✔ Refresh fails → logout once<br> ✔ No infinite loops<br> ✔ Clean UX</p><h3>🧠 Interview-Ready Summary</h3><blockquote><em>Access token expiry is handled silently using refresh tokens on a 401 response. Refresh token expiry ends the session, triggering a forced logout with a clear user message. This approach is secure, scalable, and industry-standard.</em></blockquote><h3>🏁 Final Takeaway</h3><p>If you remember only one thing:</p><pre>401 from API → Try refresh<br>Refresh fails → Session expired → Logout</pre><p>That’s it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c378fc41bdb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How Multipoint Earbuds Manage Multi-Device Connections (A Software Architect’s Deep Dive)]]></title>
            <link>https://scripturesintech.medium.com/how-multipoint-earbuds-manage-multi-device-connections-a-software-architects-deep-dive-20c7b8701053?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/20c7b8701053</guid>
            <category><![CDATA[earbuds-architecture]]></category>
            <category><![CDATA[bluetooth-multipoint]]></category>
            <category><![CDATA[a2dp-hfp]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 14:10:18 GMT</pubDate>
            <atom:updated>2025-12-13T14:10:18.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGbrL5VDPjeAYsemYSXTsw.png" /></figure><p>Most people think earbuds just “switch automatically” between devices.<br> But behind the scenes, there is a smart coordination engine built using <strong>Bluetooth protocols</strong>, <strong>event-driven routing</strong>, and a <strong>priority-based state machine</strong>.</p><p>Let’s break this down from a software architecture perspective — in a way that is readable for developers, architects, and tech enthusiasts.</p><h3>1. The Key Concept: Multipoint Isn’t Just Multiple Connections</h3><p>Multipoint earbuds do <strong>two things simultaneously</strong>:</p><ol><li>Maintain <strong>multiple Bluetooth connections</strong> at the same time (e.g., laptop + phone).</li><li>Decide <strong>which device’s audio should be active</strong> at any moment.</li></ol><p>These two abilities are completely separate.<br> Simply connecting is easy — <strong>deciding which device gets priority is the real intelligence</strong>.</p><h3>2. The Hidden Brain: Event-Driven State Machine</h3><p>Inside every multipoint earbud is a small firmware-based <strong>state machine</strong>.<br> It constantly listens for events like:</p><ul><li>A phone call ringing</li><li>A device starting media playback</li><li>A device pausing or stopping</li><li>Bluetooth profile activation (e.g., call profile becoming active)</li></ul><p>Each event changes the internal “state” of the earbuds.</p><p>The state machine’s job is simple:</p><p><strong>“When multiple devices want attention, select the highest-priority event.”</strong></p><h3>3. The Secret Logic: Priority-Based Audio Routing</h3><p>Every earbud brand uses a priority order similar to this:</p><ol><li><strong>Calls</strong></li><li><strong>Voice communication apps</strong></li><li><strong>Media (music/video)</strong></li><li><strong>Notifications</strong></li></ol><p>Why this order?</p><p>Because call audio uses a different Bluetooth profile that inherently signals urgency to the earbuds. When a call arrives, the earbuds can detect it <strong>even before your phone shows the ringing UI</strong>.</p><p>This is why music on your laptop pauses instantly.</p><h3>4. Architecture Diagram (Text-Based)</h3><p>Here is a diagram you can directly put in a blog — clean, readable, no graphics required:</p><pre>                +-------------------------+<br>                |     PHONE (Device B)    |<br>                |  - Call audio events    |<br>                |  - Media playback       |<br>                +------------+------------+<br>                             |<br>                             | Bluetooth Events (HFP, A2DP, BLE)<br>                             |<br>                +------------v-------------+<br>                |   EARBUD ROUTING CORE    |<br>                |                          |<br>                |  1. Event Listener       |<br>                |  2. State Machine        |<br>                |  3. Priority Engine      |<br>                |  4. Audio Router         |<br>                +------------+-------------+<br>                             |<br>                             | Bluetooth Events (A2DP, AVRCP)<br>                             |<br>                +------------v-------------+<br>                |    LAPTOP (Device A)     |<br>                |  - Media playback        |<br>                |  - System sounds         |<br>                +--------------------------+</pre><h3>How to read this diagram:</h3><ul><li>Both laptop and phone send independent Bluetooth signals.</li><li>Earbuds do not “poll” — they <strong>react to events</strong>.</li><li>The central <strong>Routing Core</strong> decides which stream wins based on priority.</li></ul><h3>5. How Switching Actually Works (Narrative Flow)</h3><p>Let’s use your scenario:<br> You’re watching a video on your laptop; phone receives a video call.</p><h3>What happens inside the earbuds:</h3><p><strong>Step 1 — Laptop is active</strong></p><ul><li>Earbuds are receiving A2DP (media audio)</li><li>State = “Media Playback (Laptop)”</li></ul><p><strong>Step 2 — Phone starts ringing</strong></p><ul><li>Earbuds receive a Bluetooth HFP event:</li><li>“Incoming call detected”</li></ul><p><strong>Step 3 — Priority engine runs</strong></p><ul><li>Calls &gt; Media</li><li>Call becomes the “active source”</li></ul><p><strong>Step 4 — Earbuds internally suspend laptop audio</strong><br> (No disconnect, just a temporary routing block)</p><p><strong>Step 5 — Earbuds shift audio routing to phone</strong></p><ul><li>HFP becomes active</li><li>You hear ringtone and answer</li></ul><p><strong>Step 6 — Call ends</strong></p><ul><li>HFP is released</li><li>State machine restores previous A2DP stream from the laptop</li><li>Laptop video/audio resumes automatically</li></ul><p>This smooth transition is not a connection change — <br> It’s <strong>a routing decision</strong>.</p><h3>6. Why This Is Hard to Build (Architect-Level Insight)</h3><p>There are three deeper technical challenges:</p><h3>1. Bluetooth profiles were not originally designed for true multipoint</h3><p>Engineers had to create custom logic to manage multiple audio profiles simultaneously.</p><h3>2. Every OS behaves differently</h3><p>Android, iOS, macOS, and Windows send very different metadata.<br> Earbuds must normalize these signals into <strong>consistent internal events</strong>.</p><h3>3. Switching must feel instantaneous</h3><p>Earbuds must handle:</p><ul><li>Codec changes</li><li>Buffer cleanup</li><li>Stream negotiation</li><li>Audio resync</li></ul><p>all in under 300–500 ms.</p><p>This is why <strong>the audio routing engine is often the most critical firmware module</strong> inside earbuds.</p><h3>7. How This Can Be Improved (Future Designs)</h3><p>As architects, we naturally think about improving this system.<br> Here are future-forward enhancements that real manufacturers could adopt:</p><h3>1. AI-Based Contextual Recognition</h3><p>Earbuds could detect:</p><ul><li>Are you watching a movie?</li><li>Are you in a meeting?</li><li>Are you gaming?</li><li>Is the phone call from a VIP contact?</li></ul><p>And switch intelligently, not blindly.</p><h3>2. User-Configurable Priority Profiles</h3><p>Imagine creating your own audio priority modes:</p><ul><li>“Work Mode: Laptop &gt; Phone unless it’s a call”</li><li>“Travel Mode: Phone always wins”</li><li>“Focus Mode: Don’t interrupt my media unless emergency”</li></ul><p>Today’s earbuds force you into fixed priority rules.</p><h3>3. Richer OS-Level Metadata</h3><p>Android and Windows could expose richer event signals such as:</p><ul><li>Foreground app state</li><li>Whether content is “critical” (e.g., exams, meetings)</li><li>Full-screen video flags</li></ul><p>Better metadata → Better routing.</p><h3>4. Bluetooth LE Audio Evolution</h3><p>LE Audio (LC3 codec) allows:</p><ul><li>Multiple synchronized streams</li><li>Dynamic switching</li><li>Lower latency</li><li>Better event signals</li></ul><p>This will massively improve multipoint behavior in the next 2–3 years.</p><h3>8. Final Takeaway</h3><p>Multipoint earbuds look simple, but internally they use:</p><ul><li>Event-driven firmware</li><li>A priority-based state machine</li><li>Smart audio routing logic</li><li>Bluetooth profile negotiation</li><li>Real-time decision making</li></ul><p>This is what makes them feel “intelligent.”</p><p>The next evolution will move from <strong>static rules</strong> to <strong>context-aware, user-customizable, AI-assisted audio routing</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20c7b8701053" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Dart Concurrency: A Complete Developer’s Guide to Async, Await, Isolates & Background…]]></title>
            <link>https://scripturesintech.medium.com/mastering-dart-concurrency-a-complete-developers-guide-to-async-await-isolates-background-d6d2cc548bae?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6d2cc548bae</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-concurrency]]></category>
            <category><![CDATA[isolates-in-flutter]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 16:36:02 GMT</pubDate>
            <atom:updated>2025-12-12T16:36:02.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Dart Concurrency: A Complete Developer’s Guide to Async, Await, Isolates &amp; Background Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3KaHL8Tt5fHJc0CTEClog.png" /></figure><p>Flutter apps feel fast not because the code magically runs in parallel, but because Dart uses a highly optimized concurrency model built around <strong>asynchronous I/O, the event loop, and isolates</strong>.<br> Yet most developers only know async/await and compute().</p><p>This guide takes you from beginner to expert — explaining <strong>how Dart concurrency actually works</strong>, when to use which tool, and how to architect background work like a senior Flutter engineer.</p><h3>1. Understanding Why Concurrency Matters in Dart</h3><p>Flutter renders UI at <strong>60–120 FPS</strong>.<br> That means every frame must complete in <strong>~16 ms</strong>.</p><p>If your app does anything heavy — JSON parsing, image decoding, ML inference, encryption — the <strong>UI thread (main isolate)</strong> freezes. Animations drop. Touches lag. The app “feels slow.”</p><p>Dart solves this by offering two paths:</p><ol><li><strong>Non-blocking async I/O</strong> (no extra thread needed)</li><li><strong>Parallel execution using isolates</strong> (multi-core CPU work)</li></ol><p>You must choose the right path based on the work type.</p><h3>2. Dart’s Concurrency Model in Simple Words</h3><p>Unlike languages with shared-memory threads (Swift, Java, Kotlin), Dart uses <strong>isolates</strong>.</p><h3>What is an isolate?</h3><ul><li>A separate Dart “mini-VM”</li><li>Has its <strong>own memory heap</strong></li><li>Has its <strong>own event loop</strong></li><li>Does not share objects with other isolates</li><li>Communicates via <strong>messages</strong></li></ul><p>This makes Dart inherently <strong>thread-safe</strong>:<br> No locks, no race conditions, no thread contention.</p><h3>But is Dart single-threaded?</h3><p>No.<br> The main isolate is single-threaded, but Dart can run <strong>multiple isolates in parallel</strong>, each on different CPU cores.</p><h3>3. The Three Pillars of Dart Concurrency</h3><p>There are three ways work executes in Dart:</p><ol><li><strong>Async I/O (Futures, async/await)</strong></li><li><strong>Temporary worker isolates via </strong><strong>compute()</strong></li><li><strong>Manually spawned, long-lived isolates</strong></li></ol><p>Let’s go deep.</p><h3>4. Pillar 1: Async &amp; Await — Non-Blocking I/O</h3><p>Async I/O is perfect for:</p><ul><li>Reading files</li><li>Network calls</li><li>Database operations</li><li>Delays &amp; timers</li></ul><p>These operations <em>do not block the main isolate</em>.<br> They run on Dart’s underlying system/VM threads.</p><p>Example:</p><pre>final data = await File(&#39;big.jpg&#39;).readAsBytes();</pre><p>Even a 20MB file read won’t block UI — because the I/O runs outside the isolate.</p><h3>When to use async/await:</h3><ul><li>Any <strong>I/O-bound</strong> work</li><li>When work is not CPU-heavy</li><li>When waiting is the only thing happening</li></ul><p>Async work does <strong>not</strong> use more CPU cores.<br> It just <strong>keeps the UI free</strong>.</p><h3>5. Pillar 2: compute() — Short-Lived Background Work</h3><p>CPU-heavy work <strong>must not</strong> be done in the main isolate because it blocks rendering.</p><p>Use compute() when:</p><ul><li>Work is <strong>CPU-bound</strong></li><li>A one-off task</li><li>Not reused repeatedly</li></ul><p>Example: parsing a big JSON file.</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;dart:convert&#39;; <br><br>Map&lt;String, dynamic&gt; parseJson(String raw) =&gt; jsonDecode(raw);<br>final map = await compute(parseJson, rawJson);</pre><h3>Why compute() works well:</h3><ul><li>Spawns a background isolate for you</li><li>Runs work in parallel</li><li>Moves CPU load off UI thread</li></ul><h3>Limitations:</h3><ul><li>Only top-level/static functions allowed</li><li>Data is copied to another isolate</li><li>Costly if called very frequently (isolate spawn overhead)</li></ul><p>So it’s perfect for:</p><ul><li>Large JSON parsing</li><li>Heavy image filters</li><li>Compression/decompression</li></ul><p>But not for repeated or continuous tasks.</p><h3>6. Pillar 3: Manual Isolates — Persistent Background Workers</h3><p>This is where real power comes in.</p><p>If you need:</p><ul><li>A <strong>long-running</strong> worker</li><li>Continuous processing</li><li>Real-time heavy computation</li><li>Pipelined work (send → process → send → repeat)</li><li>Lower overhead compared to repeatedly calling compute()</li></ul><p>…then create a <strong>manual isolate</strong>.</p><h3>Step-by-step example</h3><p><strong>Worker isolate entrypoint:</strong></p><pre>import &#39;dart:isolate&#39;;<br><br>void worker(SendPort mainSendPort) {<br>  final workerReceivePort = ReceivePort();<br>  mainSendPort.send(workerReceivePort.sendPort);<br>  workerReceivePort.listen((message) {<br>    final data = message[0];<br>    final SendPort reply = message[1];<br>    final result = _heavyCalculation(data);<br>    reply.send(result);<br>  });<br>}<br>int _heavyCalculation(int n) {<br>  var sum = 0;<br>  for (var i = 0; i &lt; n; i++) sum += i;<br>  return sum;<br>}</pre><p><strong>Main isolate:</strong></p><pre>final receivePort = ReceivePort(); <br><br>// Spawn worker<br>final isolate = await Isolate.spawn(worker, receivePort.sendPort);<br>// Get worker channel<br>final SendPort workerPort = await receivePort.first;<br>// Send data<br>final response = ReceivePort();<br>workerPort.send([100000000, response.sendPort]);<br>// Get result<br>final result = await response.first;<br>print(result);<br>// Kill when done<br>isolate.kill(priority: Isolate.immediate);</pre><h3>Why manual isolates are powerful</h3><ul><li>Reusable</li><li>Persistent</li><li>Low latency</li><li>Great for parallelism</li><li>Fully customizable</li></ul><p>Perfect for:</p><ul><li>Realtime ML inference</li><li>Continuous image/video processing</li><li>Heavy game logic (chess engines, physics sims)</li><li>Worker pools</li></ul><h3>7. How Dart Executes Async Work Internally</h3><h3>Event loop handles:</h3><ul><li>Future completion</li><li>Microtasks</li><li>Timers</li><li>I/O events</li></ul><h3>Isolates handle:</h3><ul><li>CPU-bound work</li><li>Parallel execution</li><li>Separate heaps</li></ul><p>They work <em>together</em> to make apps smooth.</p><h3>8. Communication Between Isolates</h3><p>Dart isolates cannot share memory.<br> Every message is copied.</p><p>Types you can send:</p><ul><li>Primitives</li><li>Lists/Maps with sendable values</li><li>TypedData (fast path)</li><li>SendPort (for channels)</li></ul><p>If you send huge structures frequently → performance drops.</p><p>Optimize by</p><ul><li>Sending small payloads</li><li>Using typed data (Uint8List)</li><li>Batching tasks</li></ul><h3>9. Practical Rules You Should Follow</h3><p>Here are battle-tested rules used in production Flutter apps.</p><h3>Rule 1: Anything &gt; 16ms → move off main isolate</h3><p>Use DevTools’ CPU profiler to inspect slow frames.</p><h3>Rule 2: I/O-bound → async/await</h3><p>No isolates needed for network/file/db work.</p><h3>Rule 3: One-off CPU-bound → compute()</h3><p>Avoid repeating compute() for batching—use manual isolate instead.</p><h3>Rule 4: Repeated CPU-bound → manual isolate</h3><p>Stable, fast, and avoids constant isolate spawning.</p><h3>Rule 5: Background execution (app closed) → WorkManager</h3><p>Not the same as isolates.<br> WorkManager spawns a <strong>background Dart isolate</strong> with limitations.</p><h3>Rule 6: Do not call Flutter plugins inside spawned isolates</h3><p>Most plugins only work on the main isolate.</p><h3>10. Real-World Examples</h3><h3>Use cases for async I/O:</h3><ul><li>Firestore read</li><li>File download</li><li>SQLite query</li><li>API call</li></ul><h3>Use cases for compute():</h3><ul><li>JSON parsing</li><li>Thumbnail generation</li><li>Resizing images</li><li>Small ML preprocessing</li></ul><h3>Use cases for manual isolate:</h3><ul><li>Map generation (games)</li><li>Video frame filtering</li><li>Data encryption batch processing</li><li>Large array computations</li><li>Real-time ML inference</li></ul><h3>11. When Dart Concurrency Fails (Common Mistakes)</h3><p>Many developers misuse concurrency and create performance regressions.</p><p>Avoid these:</p><h3>Mistake 1: Doing heavy work in build()</h3><p>Never do synchronous CPU work inside UI lifecycle.</p><h3>Mistake 2: Using compute() in loops</h3><p>This spawns too many isolates → CPU thrashing.</p><h3>Mistake 3: Sending huge data between isolates</h3><p>Copying 50MB images kills performance.</p><h3>Mistake 4: Expecting isolates to run platform APIs</h3><p>They don’t. Only the main isolate can interact with Flutter engine &amp; plugins.</p><h3>12. Patterns for Production</h3><h3>Pattern: Persistent Worker</h3><p>Create a worker isolate during app startup and reuse it for all CPU-heavy work.</p><h3>Pattern: Worker Pool</h3><p>Spawn multiple isolates to balance large work sets (parallel chunk processing).</p><h3>Pattern: Stream Processing</h3><p>Use isolates to consume and transform data streams with low latency.</p><h3>13. Final Summary — Dart Concurrency in One Paragraph</h3><p>Dart achieves smooth app performance by combining <strong>non-blocking async I/O</strong> with <strong>parallel CPU execution through isolates</strong>.<br> Use async/await for network and file work, compute() for one-off heavy tasks, and manual isolates for long-running or repetitive CPU-bound computations. Dart isolates guarantee thread-safety by preventing shared mutable memory, and background work outside app lifecycle is handled by platform-specific schedulers like WorkManager.<br> Mastering this model lets you architect fast, scalable, and jank-free Flutter apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6d2cc548bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How Widgets, Elements & RenderObjects Work in Flutter]]></title>
            <link>https://scripturesintech.medium.com/how-widgets-elements-renderobjects-work-in-flutter-8dd49b06f987?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd49b06f987</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 07:52:12 GMT</pubDate>
            <atom:updated>2025-12-11T07:52:12.951Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete, simplified, and accurate deep-dive tutorial</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgU6Gv9GdcFQgWYF9hFVeQ.png" /></figure><p>Flutter is famous for its smooth performance and declarative UI. But have you ever wondered <em>how</em> Flutter converts your widgets into pixels on the screen?</p><p>The secret lies in three powerful structures:</p><ul><li>The <strong>Widget Tree</strong></li><li>The <strong>Element Tree</strong></li><li>The <strong>RenderObject Tree</strong></li></ul><p>These three layers work together to create, update, and paint your interface efficiently.</p><p>This tutorial explains each step as Flutter moves from your Dart code → to actual rendering on screen.</p><h3>1. Everything starts with Widgets</h3><p>You’ve heard it many times: <strong>“In Flutter, everything is a widget.”</strong><br> But what does that actually mean?</p><p>Widgets are simply <strong>immutable configuration objects</strong>.<br> They describe <em>what</em> your UI should look like, but they don’t store any state, position, or size.</p><p>A widget:</p><ul><li>has no lifecycle</li><li>cannot change internally because it’s immutable</li><li>is replaced on every build() call</li><li>is extremely lightweight</li></ul><p>Example:</p><pre>Text(<br>  &quot;Hello Flutter&quot;,<br>  style: TextStyle(fontSize: 20),<br>);d</pre><p>This widget tells Flutter:</p><blockquote><em>I want a text with font size 20, rendered somewhere by the system.</em></blockquote><p>That’s all. No magic. No state. No position.<br> It’s just a <em>blueprint</em>.</p><h3>2. The Element Tree — Flutter’s invisible engine</h3><p>Since widgets are immutable, Flutter needs something that can:</p><ul><li>remember where widgets are in the UI tree</li><li>store their lifecycle</li><li>trigger rebuilds</li><li>keep state alive</li><li>know when to update or reuse something</li></ul><p>This “behind-the-scenes” machinery is called the <strong>Element Tree</strong>.</p><p>Every time a widget is inserted into the UI, Flutter creates an <strong>Element</strong> for it.</p><p>An Element:</p><ul><li>is <strong>mutable</strong></li><li>is the real connection between widget and rendering</li><li>stores the widget’s position in the tree</li><li>manages the widget’s lifecycle</li><li>holds State objects for StatefulWidgets</li><li>performs reconciliation when the UI updates</li></ul><p>When your app rebuilds:</p><ul><li>widgets are <strong>recreated</strong></li><li>Elements are <strong>reused</strong> whenever possibl</li></ul><p>This reuse is what makes Flutter extremely fast.</p><h3>3. The RenderObject Tree — where UI is actually drawn</h3><p>RenderObjects handle the heavy work:</p><ul><li>measuring size</li><li>laying out children</li><li>computing offsets</li><li>drawing on the canvas</li><li>hit testing for gestures</li></ul><p>A RenderObject:</p><ul><li>is <strong>mutable</strong></li><li>persists as long as possible</li><li>updates only when necessary</li><li>is expensive to recreate, so Flutter tries to reuse it</li></ul><p>Examples of RenderObjects:</p><ul><li>RenderParagraph for Text</li><li>RenderFlex for Row and Column</li><li>RenderConstrainedBox for SizedBox</li><li>RenderPadding for Padding</li></ul><p>Widgets → describe<br> Elements → manage<br> RenderObjects → render</p><h3>4. How all three work together</h3><p>Let’s start with a simple widget tree:</p><pre>Padding(<br>  padding: EdgeInsets.all(8),<br>  child: Text(&quot;Hello World&quot;),<br>)</pre><p>When Flutter builds this, the following happens:</p><h3>Step 1: Flutter creates the Widget Tree</h3><p>A Padding widget containing a Text widget.</p><h3>Step 2: Flutter creates the Element Tree</h3><ul><li>Padding → RenderObjectElement</li><li>Text → LeafRenderObjectElement</li></ul><p>Each widget now has a live Element managing it.</p><h3>Step 3: Flutter creates the RenderObject Tree</h3><ul><li>Padding widget creates a RenderPadding</li><li>Text widget creates a RenderParagraph</li></ul><p>The RenderObject tree is what the Flutter engine will use to compute layout and paint pixels.</p><h3>5. What happens when something changes?</h3><p>This is where Flutter shines.</p><p>Consider this simple StatefulWidget:</p><pre>setState(() {<br>  message = &quot;Hello Again&quot;;<br>});</pre><p>Flutter rebuilds the widget tree:</p><ul><li>old Text widget → new Text widget</li><li>they have the same type (Text)</li><li>the Element is reused</li><li>the RenderObject (RenderParagraph) is updated with new text</li><li>only that subtree is repainted</li></ul><p>No need to rebuild the entire UI.</p><p>This process is called <strong>reconciliation</strong>.</p><p>Flutter compares:</p><ol><li>old widget vs new widget</li><li>do they have the same type? same key?</li><li>if yes → reuse Element and RenderObject</li><li>if no → destroy and rebuild only that part</li></ol><p>This selective updating is why Flutter apps feel fast and responsive.</p><h3>6. StatefulWidget vs StatelessWidget under the hood</h3><h3>StatelessWidget</h3><ul><li>Widget is recreated every build</li><li>Element is reused if type and key match</li><li>No internal state</li><li>RenderObjects update only if configuration change</li></ul><h3>StatefulWidget</h3><p>A StatefulWidget consists of:</p><ol><li><strong>StatefulWidget</strong> → immutable configuratio</li><li><strong>State</strong> → mutable object stored inside its Element</li></ol><p>The State object lives as long as:</p><ul><li>the Element persists</li><li>the widget’s runtime type and key stay the same</li></ul><p>This is why state survives rebuilds.</p><h3>7. Why Flutter uses three trees</h3><p>Most UI frameworks use a single tree. Flutter uses three for performance and clarity.</p><h3>Widgets</h3><p>Describe configurations. Cheap. Immutable. Disposable.</p><h3>Elements</h3><p>Manage lifecycle, hold state, and perform reconciliation.</p><h3>RenderObjects</h3><p>Do all rendering and layout work. Expensive, so they must be reused.</p><p>This separation allows Flutter to:</p><ul><li>update only what is necessary</li><li>skip unnecessary rebuilds</li><li>keep the UI fast even with thousands of widget</li><li>maintain stable state during updates</li><li>perform efficient diffing (reconciliation)</li></ul><h3>8. Real-life example of reuse</h3><p>Imagine a Column containing many children:</p><pre>Column(<br>  children: [<br>    Text(&quot;Hello&quot;),<br>    Text(&quot;World&quot;),<br>    Text(count.toString()),<br>  ],<br>)</pre><p>When count changes:</p><ul><li>only the last Text widget changes</li><li>Flutter does not rebuild or repaint the first two</li><li>Elements for unchanged widgets remain</li><li>RenderObjects for unchanged widgets remain</li><li>Only the last text’s RenderParagraph updates</li></ul><p>This is real efficiency.</p><h3>9. Key takeaways</h3><ul><li>Widgets are immutable and disposable</li><li>Elements are the backbone of Flutter’s widget lifecycle</li><li>RenderObjects do layout and painting</li><li>setState() triggers a rebuild of widgets but not Elements or RenderObjects unless required</li><li>Reconciliation ensures only necessary parts update</li></ul><p>Flutter’s architecture is designed for both flexibility and raw performance.</p><h3>10. Final summary</h3><p>Flutter converts your UI code into pixels through this pipeline:</p><ol><li><strong>Widget Tree</strong> — you write it. Pure configuration.</li><li><strong>Element Tree</strong> — manages widget lifecycle, holds State, performs updates.</li><li><strong>RenderObject Tree</strong> — performs layout and paints on the screen.</li></ol><p>This layered system is what makes Flutter:</p><ul><li>fast</li><li>predictable</li><li>declarative</li><li>efficient for animations</li><li>powerful for large UIs</li></ul><p>If you understand these three trees, you understand Flutter’s core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd49b06f987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Kotlin Class Types: When to Use What & Why — A Developer’s Guide]]></title>
            <link>https://scripturesintech.medium.com/mastering-kotlin-class-types-when-to-use-what-why-a-developers-guide-47a2e492401d?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a2e492401d</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 07:19:01 GMT</pubDate>
            <atom:updated>2025-12-11T07:19:01.125Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧩 Mastering Kotlin Class Types: When to Use What &amp; Why — A Developer’s Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrSE8wNjUg3jobWc20qwNQ.png" /></figure><p>Kotlin gives us multiple types of classes — each solving a specific problem in software architecture. Knowing <strong>when to use which class</strong> is a hallmark of writing clean, scalable Kotlin code.</p><p>This guide breaks it down with practical use cases and examples you can apply immediately in Android, backend, or any Kotlin project.</p><h3>1️⃣ Regular Class — When You Just Need a Blueprint</h3><p>A <strong>regular class</strong> is the most straightforward structure.<br> Use it when you want to represent a real-world object with behavior and state.</p><h3>Example</h3><pre>class Person(val name: String, var age: Int) {<br>    fun celebrateBirthday() {<br>        age++<br>    }<br>}</pre><p><strong>Use When</strong></p><ul><li>You need objects with behavior (methods)</li><li>No special functionality like comparison or state handling is required</li></ul><h3>2️⃣ Data Class — Best for Pure Data Models</h3><p>If your class mainly holds data and needs automatic:</p><ul><li>equals()</li><li>hashCode()</li><li>toString()</li><li>copy()</li></ul><p>…then a <strong>data class</strong> is the best choice.</p><h3>Example (Common in APIs or Database models)</h3><pre>data class User(val id: Int, val name: String)</pre><p><strong>Use When</strong></p><ul><li>You are modeling DTOs, response models, local entities</li><li>You want value-based comparison instead of reference comparison</li></ul><p>📌 Ideal in Android for <strong>Room Entities</strong>, <strong>State objects</strong>, <strong>Network Models</strong>.</p><h3>3️⃣ Abstract Class — When You Need a Base Template</h3><p>An <strong>abstract class</strong> defines a foundation but leaves details to subclasses.</p><h3>Example</h3><pre>abstract class Shape {<br>    abstract fun area(): Double<br>}<br><br>class Circle(private val radius: Double) : Shape() {<br>    override fun area() = Math.PI * radius * radius<br>}</pre><p><strong>Use When</strong></p><ul><li>You want shared functionality + must-implement functions</li><li>You need constructor parameters that can be reused across child classes</li></ul><p>📌 Especially useful in architecture patterns (base views, base repositories)</p><h3>4️⃣ Interface — When You Want Flexible Behavior Contracts</h3><p>Unlike abstract classes, an <strong>interface</strong> allows multi-inheritance of behaviors.<br> Great for defining capabilities.</p><h3>Example</h3><pre>interface Clickable {<br>    fun onClick()<br>}<br><br>class Button : Clickable {<br>    override fun onClick() = println(&quot;Button clicked&quot;)<br>}</pre><p><strong>Use When</strong></p><ul><li>You are modeling behavior and don’t need state</li><li>You want multiple inheritance support</li></ul><p>📌 Very common in Android UI and event-driven systems</p><h3>5️⃣ Sealed Class — Modeling Limited States</h3><p>A <strong>sealed class</strong> restricts subclassing within the same file.<br> Perfect for <strong>handling results or state machines</strong>.</p><h3>Example — API Response Result</h3><pre>sealed class ApiResult {<br>    data class Success(val data: String) : ApiResult()<br>    data class Failure(val error: String) : ApiResult()<br>    object Loading : ApiResult()<br>} <br><br>fun handle(result: ApiResult) {<br>    when(result) {<br>        is ApiResult.Success -&gt; println(&quot;Data: ${result.data}&quot;)<br>        is ApiResult.Failure -&gt; println(&quot;Error: ${result.error}&quot;)<br>        ApiResult.Loading -&gt; println(&quot;Please wait...&quot;)<br>    }<br>}</pre><p><strong>Use When</strong></p><ul><li>You want safe exhaustive when handling</li><li>Limited and defined set of types</li></ul><p>📌 Perfect for MVI/MVVM states in Android</p><h3>6️⃣ Enum Class — Limited Constants With Logic</h3><p>Use <strong>Enums</strong> when you have predefined constant values.</p><h3>Example</h3><pre>enum class LogLevel {<br>    ERROR, WARN, INFO<br>}</pre><p>Enum classes can also contain functions or properties — great for behavior-based constants.</p><p><strong>Use When</strong></p><ul><li>You have a fixed number of states that won’t grow</li><li>Example: traffic light colors, user roles, directions</li></ul><h3>7️⃣ Object Declaration — When You Need a Singleton</h3><p>A Kotlin object creates <strong>exactly one instance</strong> — thread-safe by default.</p><h3>Example — Logger Singleton</h3><pre>object Logger {<br>    fun log(msg: String) = println(&quot;Log: $msg&quot;)<br>}</pre><p><strong>Use When</strong></p><ul><li>Shared global instance needed</li><li>Avoid static helper classes like in Java</li></ul><p>📌 Perfect for configuration managers, API clients (if no DI used)</p><h3>8️⃣ Companion Object — Class-Level Members</h3><p>Alternative for Java static members.</p><h3>Example</h3><pre>class Car {<br>    companion object {<br>        fun create() = Car()<br>    }<br>}</pre><p><strong>Use When</strong></p><ul><li>You need a factory method</li><li>Constants or utilities belong to class, not objects</li></ul><h3>9️⃣ Nested &amp; Inner Classes — Structuring Complex Classes</h3><h3>Nested Class</h3><p>No access to outer class instance</p><pre>class Outer {<br>    class Nested {<br>        fun msg() = &quot;I&#39;m nested&quot;<br>    }<br>}</pre><h3>Inner Class</h3><p>Has reference to outer class</p><pre>class Outer {<br>    val value = &quot;Outer class&quot;<br><br>inner class Inner {<br>        fun show() = value<br>    }<br>}</pre><p><strong>Use When</strong></p><ul><li>You want logical grouping of classes</li><li>Inner classes only if they require outer class data</li></ul><h3>10️⃣ Generic Class — Reusable Type-Safe Containers</h3><p>Generics allow building classes that work with different types.</p><pre>class Box&lt;T&gt;(val item: T)<br><br>val intBox = Box(10)<br>val stringBox = Box(&quot;Hello</pre><p><strong>Use When</strong></p><ul><li>You need type flexibility without sacrificing type safety</li></ul><p>📌 Used heavily in collections and reusability patterns</p><h3>🏁 Final Thoughts</h3><p>Choosing the right Kotlin class type isn’t syntax — it’s <strong>design thinking</strong>.</p><p>Ask yourself:</p><ul><li>Is this just data? → <strong>Data class</strong></li><li>Is this shared functionality? → <strong>Abstract class</strong></li><li>Is this a behavior contract? → <strong>Interface</strong></li><li>Is this a limited set of states? → <strong>Sealed / Enum</strong></li><li>Do I need only one instance? → <strong>Object</strong></li><li>Do I need static behavior? → <strong>Companion object</strong></li><li>Do I need a simple model with behavior? → <strong>Regular class</strong></li></ul><p>Proper class selection leads to:<br> ✔ Cleaner architecture<br> ✔ Better scalability<br> ✔ Safer and more maintainable code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a2e492401d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leading Agile Teams with H.E.A.R.T.: A Practical Leadership Framework for High-Quality Delivery]]></title>
            <link>https://scripturesintech.medium.com/leading-agile-teams-with-h-e-a-r-t-a-practical-leadership-framework-for-high-quality-delivery-d98b3cfc7720?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d98b3cfc7720</guid>
            <category><![CDATA[leadership-development]]></category>
            <category><![CDATA[agile-methodology]]></category>
            <category><![CDATA[scrum-master]]></category>
            <category><![CDATA[scrum]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 23:59:01 GMT</pubDate>
            <atom:updated>2025-12-09T23:59:01.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIuqmlOjaOuYs3KBU4Gg3g.png" /></figure><p>Great Agile teams don’t succeed because they have perfect processes.<br> They succeed because they are led in a way that brings the best out of people <strong>while refusing to compromise standards.</strong></p><p>To achieve this consistently, leaders need more than empathy — they need a leadership system.</p><p>Introducing the <strong>H.E.A.R.T. Framework</strong>:</p><blockquote><strong><em>Humanity • Expectations • Accountability • Rituals • Technical Excellence</em></strong></blockquote><p>A framework built to help leaders grow people, elevate outcomes, and ensure every shipped product represents true craftsmanship.</p><p>Below, we break down each pillar with <strong>real use cases and leadership actions</strong> that readers can start using tomorrow.</p><h3>1️⃣ Humanity — Because People Deliver Outcomes</h3><p>Agile is built on human collaboration.<br> When individuals trust their leader and each other, delivery accelerates.</p><h3>Leadership Behaviors</h3><ul><li>Ask “How are you doing?” before “What’s the status?”</li><li>Clarify team members’ strengths and give them roles that energize them</li><li>Recognize silent suffering — not everyone speaks when struggling</li></ul><h3>Use Case</h3><p>A developer misses two sprint commitments. Instead of assuming laziness:</p><p><strong>Bad leadership response:</strong><br> “Why can’t you finish what you commit to?”</p><p><strong>H.E.A.R.T. response:</strong><br> “Help me understand what’s making this harder than expected — let’s unblock you.”</p><p>Outcome:<br> Hidden blockers surface — unclear requirements, tech complexity, divided focus.<br> With support, performance rebounds <strong>without damage to confidence</strong>.</p><p>Humanity creates the psychological safety required for honesty, improvement, and ownership.</p><h3>2️⃣ Expectations — Clarity that Drives Performance</h3><p>Teams fail not because they lack skills, but because they lack clarity.</p><h3>Leadership Behaviors</h3><ul><li>Define outcomes, not just outputs</li><li>Align success criteria at the start of every sprint</li><li>Model excellence — don’t just demand it</li></ul><h3>Use Case</h3><p>Instead of “Add login feature,” define:</p><ul><li>What success looks like (e.g., secure, fast authentication)</li><li>Who benefits (new users, returning customers)</li><li>Acceptance criteria (error scenarios, password policies)</li></ul><p>Outcome:<br> Rework is avoided. Quality is inherent. Everyone knows the target from day one.</p><p>Clarity <strong>reduces friction</strong>. High expectations <strong>raise performance</strong>.</p><h3>3️⃣ Accountability — Trust and Transparency in Action</h3><p>Accountability is not punishment — it is shared discipline.</p><h3>Leadership Behaviors</h3><ul><li>Raise issues privately, celebrate successes publicly</li><li>Review commitments and outcomes consistently</li><li>Teach ownership, not dependency</li></ul><h3>Use Case</h3><p>If a team member silently struggles every sprint:</p><p><strong>Instead of:</strong><br> “It’s fine, we’ll pick it up next sprint.”</p><p><strong>Do:</strong><br> Collaboratively inspect why — workload? skills? priorities? clarity? confidence?</p><p>Then set:</p><ul><li>A learning plan (pair programming, mentoring)</li><li>A communication expectation for early signaling</li><li>A follow-up checkpoint</li></ul><p>Outcome:<br> The teammate grows. The team maintains predictability. Accountability lifts everyone, not just the top performers.</p><h3>4️⃣ Rituals — Structure That Enables High-Performance</h3><p>Agile ceremonies are not meetings — they are <strong>discipline systems</strong>.</p><h3>Leadership Behaviors</h3><ul><li>Make standups about resolving blockers, not reporting to the boss</li><li>Turn retrospectives into real change, not history lessons</li><li>Link sprint reviews to customer learning, not slide presentations</li></ul><h3>Use Case</h3><p>A team keeps missing sprint goals.<br> In retros, turn “what went wrong?” into “what will we change?”:</p><p>Change examples:</p><ul><li>Daily check-ins focused on goal alignment</li><li>Definition of Ready enforced before pulling items</li><li>Blockers escalated within 2 hours, not at sprint end</li></ul><p>Outcome:<br> Sprints don’t drift — they stay laser-aligned to outcomes.</p><p>Rituals are not about tradition…<br> They are about <strong>continuous improvement embedded into culture</strong>.</p><h3>5️⃣ Technical Excellence — Quality Is the Brand</h3><p>Speed without quality is <strong>false success</strong>.</p><h3>Leadership Behaviors</h3><ul><li>Enforce quality gates: testing, code reviews, security checks</li><li>Prioritize refactoring and automation as investments</li><li>Encourage engineering ownership of the product experience</li></ul><h3>Use Case</h3><p>A team rushes features to meet deadlines. Bugs pile up. Customers complain.</p><p>Leadership shift:</p><ul><li>Introduce automated tests each sprint</li><li>Block deployments if critical issues exist</li><li>Set performance metrics as part of acceptance criteria</li></ul><p>Outcome:<br> Velocity initially dips… then skyrockets as rework decreases.<br> Reputation improves. Stress drops. Morale rises.</p><p>Quality <strong>does not slow teams down</strong> — poor quality does.</p><h3>The H.E.A.R.T. Weekly Leadership Routine</h3><p>Here is a simple rhythm executives, managers, or Scrum Masters can adopt:</p><p><strong>Every Day</strong></p><ul><li>Ask unblocker questions: “What do you need to succeed today?”</li><li>Observe energy levels and team dynamics</li></ul><p><strong>Every Sprint</strong></p><ul><li>Challenge the team to raise one quality or speed metric</li><li>Celebrate effort and learning, not just delivery</li></ul><p><strong>Every Month</strong></p><ul><li>Review skills growth, not only velocity</li><li>Remove one systemic bottleneck (not just patch symptoms)</li></ul><p>Leadership becomes consistent, intentional, and transformative.</p><h3>Final Thought</h3><p>The best Agile leaders do more than run the process.<br> They elevate people and outcomes through structured compassion and unwavering standards.</p><p>Lead with <strong>Humanity</strong> — people do their best when they feel seen.<br> Set strong <strong>Expectations</strong> — clarity inspires excellence.<br> Foster <strong>Accountability</strong> — trust builds reliability.<br> Strengthen <strong>Rituals</strong> — discipline sustains performance.<br> Demand <strong>Technical Excellence</strong> — customers deserve quality.</p><p>This is how teams evolve from delivering features…<br> to delivering <strong>impact</strong> that shapes careers, organizations, and user experience.</p><p>Lead with H.E.A.R.T.<br> And your team will build products worth believing in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d98b3cfc7720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Letting Function0 Slow Down Your Android App: How inline, noinline and crossinline Fix Lambda…]]></title>
            <link>https://scripturesintech.medium.com/stop-letting-function0-slow-down-your-android-app-how-inline-noinline-and-crossinline-fix-lambda-f945ea311f89?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f945ea311f89</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[lambda-function]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 23:39:04 GMT</pubDate>
            <atom:updated>2025-12-09T23:39:04.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Letting Function0 Slow Down Your Android App: How inline, noinline and crossinline Fix Lambda Memory Issues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8b1Bo79cvzfNpI_kB2oIg.png" /></figure><p>Kotlin callbacks make Android code elegant — but behind the scenes, they may be creating performance issues you aren’t seeing.<br> If you’ve ever noticed something like this in logs or crash traces:</p><pre>kotlin.jvm.functions.Function0</pre><p>that’s your hint.</p><p>Let’s walk through the problem quickly, and then solve it in the smartest way.</p><h3>What is Function0 in Kotlin?</h3><p>When you define a callback with no parameters:</p><pre>val action: () -&gt; Unit = { println(&quot;Clicked!&quot;) }</pre><p>Kotlin internally sees it as:</p><pre>Function0&lt;Unit&gt;</pre><p>This happens whenever you use:</p><ul><li>Button clicks</li><li>Retry actions</li><li>Success/error callbacks</li><li>Any lambda with zero arguments</li></ul><p>So what’s the issue?</p><h3>The Memory Problem Nobody Talks About</h3><p>Every lambda becomes a <strong>real object</strong> at runtime.</p><p>Kotlin converts your lambda into a class:</p><pre>class ActionLambda : Function0&lt;Unit&gt; {<br>    override fun invoke() {<br>        println(&quot;Clicked!&quot;)<br>    }<br>}</pre><p>Meaning:</p><ul><li>New class created</li><li>New object allocated</li><li>invoke() used for every call</li></ul><p>If the function is called frequently (animations, loops, LiveData observers firing often), it:</p><ul><li>Wastes memory with repeated allocations</li><li>Triggers more garbage collection</li><li>Causes UI jank</li></ul><p>So yes, Function0 can degrade performance.</p><h3>How inline Fixes It</h3><p>Kotlin gives us a superpower:</p><pre>inline fun log(block: () -&gt; Unit) {<br>    println(&quot;Start&quot;)<br>    block()<br>    println(&quot;End&quot;)<br>}<br><br>log {<br>    println(&quot;Hello&quot;)<br>}k</pre><p>The compiler transforms this into:</p><pre>println(&quot;Start&quot;)<br>println(&quot;Hello&quot;)<br>println(&quot;End&quot;)</pre><p>There is:</p><ul><li>No Function0 object</li><li>No invoke() calls</li><li>Zero memory allocation for the lambda</li></ul><p>This is exactly why inline exists.</p><p>Inline is a <strong>performance optimization</strong>.</p><h3>But inline Comes With Its Own Limitations</h3><p>Inline lambdas cannot:</p><ol><li>Be saved in a variable</li><li>Be returned as a result</li><li>Be passed further to other functions</li></ol><p>If you try…</p><pre>inline fun perform(action: () -&gt; Unit) {<br>    val temp = action<br>}</pre><p>You’ll get a compiler error.</p><h3>When Inline Fails → Use noinline</h3><p>If a lambda must be stored or forwarded:</p><pre>inline fun perform(<br>    action: () -&gt; Unit,<br>    noinline fallback: () -&gt; Unit<br>) {<br>    val temp = fallback<br>    temp()<br>    action()<br>}</pre><p>Here:</p><ul><li>action is still optimized by inline</li><li>fallback behaves like a normal lambda object</li></ul><p>Noinline keeps flexibility<br> while letting inline do its job elsewhere.</p><h3>Another Inline Problem: Unexpected Returns</h3><p>Inline allows “return jumping”:</p><pre>inline fun doTask(block: () -&gt; Unit) {<br>    block()<br>    println(&quot;Done&quot;)<br>}<br><br>fun test() {<br>    doTask {<br>        return   // exits test()! not just block<br>    }<br>}</pre><p>This is called a <strong>non-local return</strong> and can be dangerous around:</p><ul><li>Async callbacks</li><li>Threads</li><li>Coroutines</li></ul><p>The function may exit too early and skip important code.</p><h3>When Inline Needs Safety → Use crossinline</h3><pre>inline fun doTask(crossinline block: () -&gt; Unit) {<br>    Thread {<br>        block()  // Safe: cannot break the calling function<br>    }.start()<br>}</pre><p>Crossinline ensures the callback <strong>cannot escape</strong> its scope.</p><p>This is perfect for:</p><ul><li>UI thread posting (Handler, runOnUiThread)</li><li>Coroutine callbacks</li><li>Network success actions</li></ul><p>It keeps inline performance<br> without compromising logic flow.</p><h3>Final Practical Rules You’ll Actually Use</h3><p>• When performance matters<br> → Use inline</p><p>• When storing or passing a callback for later<br> → Use noinline</p><p>• When callback runs asynchronously &amp; must not return from the caller<br> → Use crossinline</p><p>With these techniques, your app will:</p><ul><li>Create fewer lambda objects</li><li>Reduce memory churn</li><li>Avoid GC spikes</li><li>Keep UI smooth</li></ul><h3>Wrap-Up</h3><p>You can’t avoid Function0 in Kotlin — it’s how callbacks work.<br> But you <em>can</em> avoid the memory and return-flow problems it introduces.</p><p>1️⃣ Function0 objects cause memory overhead<br> 2️⃣ inline removes these objects completely<br> 3️⃣ noinline restores flexibility when inline isn’t allowed<br> 4️⃣ crossinline protects control flow in async code</p><p>Write clean lambdas — and make them fast.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f945ea311f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Modifiers: A Comprehensive Guide from Beginner to Expert]]></title>
            <link>https://scripturesintech.medium.com/swiftui-modifiers-a-comprehensive-guide-from-beginner-to-expert-d950188434e9?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d950188434e9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-modifiers]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 17:14:55 GMT</pubDate>
            <atom:updated>2025-12-08T17:14:55.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onVuvPNdilfOrSPUaa5d4A.png" /></figure><p>If you’ve written even a single line of SwiftUI, you’ve already met <strong>modifiers</strong>:</p><pre>Text(&quot;Hello, SwiftUI!&quot;)<br>    .font(.title)<br>    .foregroundColor(.blue)</pre><p>Those .font and .foregroundColor calls are modifiers. They look innocent, but understanding them deeply is one of the biggest upgrades you can give your SwiftUI skills — from beginner experiments to production-grade apps.</p><p>In this guide, we’ll go from the basics to advanced patterns:</p><ol><li>What modifiers are and how they work</li><li>Why modifier <strong>order</strong> matters</li><li>Types of modifiers (layout, style, interaction, animation, etc.)</li><li>Environment and “parent” modifiers</li><li>Conditional modifiers (if/else with clean code)</li><li>Creating reusable <strong>custom modifiers</strong></li><li>Composing complex UIs with modifiers like a pro</li><li>Common pitfalls and best practices</li></ol><p>Let’s dive in.</p><h3>1. What Is a Modifier in SwiftUI?</h3><p>At a high level:</p><blockquote><em>A </em><strong><em>modifier</em></strong><em> is a method that returns a </em><strong><em>new view</em></strong><em> based on the original view, with some change applied.</em></blockquote><p>SwiftUI views are <strong>value types</strong> (structs), not UI elements you mutate. That means when you write:</p><pre>Text(&quot;Welcome&quot;)<br>    .font(.headline)<br>    .padding()</pre><p>Under the hood, SwiftUI does something conceptually like:</p><pre>let base = Text(&quot;Welcome&quot;)<br>let withFont = base.font(.headline)      // returns a new view<br>let withPadding = withFont.padding()     // returns another new view</pre><p>Each modifier <strong>wraps</strong> the previous view in another view that represents the transformation.</p><p>You’re not changing the original Text; you’re building a <strong>view tree</strong> using a chain of transformations.</p><h3>2. The Rule Everyone Learns Late: Order Matters</h3><p>One of the first “aha!” moments with modifiers is realizing that <strong>the order of modifiers changes the result</strong>.</p><p>Example:</p><pre>// Example 1<br>Text(&quot;Hello&quot;)<br>    .font(.title)<br>    .padding()<br>    .background(Color.yellow)</pre><p>Versus:</p><pre>// Example 2<br>Text(&quot;Hello&quot;)<br>    .padding()<br>    .background(Color.yellow)<br>    .font(.title)</pre><p>You might expect the same output. They are <strong>not</strong> the same.</p><ul><li>In <strong>Example 1</strong>, the font is applied <strong>before</strong> padding, so the text grows, then padding is added, then the whole padded area gets a yellow background.</li><li>In <strong>Example 2</strong>, .font(.title) applies to the whole result of .background(Color.yellow) (and sometimes may not behave as you intuitively expect depending on the view structure).</li></ul><p>A clearer visual example:</p><pre>// Background around text only<br>Text(&quot;Hello&quot;)<br>    .background(Color.yellow)<br>    .padding()<br><br>// Background including the padding<br>Text(&quot;Hello&quot;)<br>    .padding()<br>    .background(Color.yellow)</pre><p>Keep this mental model:</p><blockquote><em>Modifiers are applied </em><strong><em>top-to-bottom</em></strong><em>, each wrapping the result of the previous one.</em></blockquote><p>When something “looks wrong” in SwiftUI, checking the <strong>modifier order</strong> is one of the fastest debugging steps.</p><h3>3. Types of Modifiers (and When to Use Them)</h3><p>SwiftUI has a huge number of modifiers, but most fall into a few categories:</p><h3>3.1 Layout Modifiers</h3><p>These control <strong>size, position, and arrangement</strong>.</p><p>Common examples:</p><pre>Text(&quot;Layout&quot;)<br>    .padding()                 // Adds internal spacing<br>    .frame(width: 200, height: 50, alignment: .center)<br>    .background(Color.gray)</pre><p>Some layout modifiers to know:</p><ul><li>padding(_:)</li><li>frame(width:height:alignment:)</li><li>offset(x:y:)</li><li>position(x:y:)</li><li>fixedSize()</li><li>layoutPriority(_:)</li></ul><p><strong>Tip:</strong> Prefer padding + flexible layouts over fixed widths/heights unless you really need exact sizes.</p><h3>3.2 Style &amp; Appearance Modifiers</h3><p>These change <strong>how things look</strong>, not where they are.</p><p>Examples:</p><pre>Text(&quot;Styled&quot;)<br>    .font(.headline)<br>    .foregroundColor(.white)<br>    .bold()<br>    .italic()<br>    .background(Color.blue)<br>    .cornerRadius(8)</pre><p>Common styling modifiers:</p><ul><li>font(_:)</li><li>foregroundColor(_:)</li><li>background(_:)</li><li>cornerRadius(_:)</li><li>opacity(_:)</li><li>shadow(radius:x:y:)</li><li>border(_:width:)</li></ul><h3>3.3 Interaction Modifiers</h3><p>These add <strong>gestures and actions</strong>.</p><pre>Text(&quot;Tap me&quot;)<br>    .onTapGesture {<br>        print(&quot;Tapped!&quot;)<br>    }<br><br>Text(&quot;Long press me&quot;)<br>    .onLongPressGesture {<br>        print(&quot;Long pressed!&quot;)<br>    }</pre><p>Other interaction modifiers:</p><ul><li>onTapGesture(count:_:)</li><li>gesture(_:)</li><li>simultaneousGesture(_:)</li><li>highPriorityGesture(_:)</li><li>onSubmit { }</li><li>onChange(of:) { }</li></ul><h3>3.4 Animation &amp; Transition Modifiers</h3><p>For smooth UI updates:</p><pre>@State private var isOn = false<br><br>Toggle(&quot;Animate me&quot;, isOn: $isOn)<br>    .padding()<br>    .background(isOn ? .green : .red)<br>    .animation(.easeInOut, value: isOn)</pre><p>Useful modifiers:</p><ul><li>animation(_:value:)</li><li>transition(_:)</li><li>withAnimation { ... } (not a modifier but works closely with them)</li></ul><h3>3.5 Accessibility Modifiers</h3><p>Don’t skip these — they’re crucial for real-world apps.</p><pre>Image(systemName: &quot;house.fill&quot;)<br>    .accessibilityLabel(&quot;Home&quot;)<br>    .accessibilityHint(&quot;Opens the home screen&quot;)</pre><p>Others:</p><ul><li>accessibilityHidden(_:)</li><li>accessibilityAddTraits(_:)</li><li>accessibilityValue(_:)</li></ul><h3>4. Environment &amp; “Parent” Modifiers</h3><p>Some modifiers don’t just affect one view; they cascade down the <strong>view hierarchy</strong>.</p><p>Example:</p><pre>VStack {<br>    Text(&quot;Hello&quot;)<br>    Text(&quot;World&quot;)<br>}<br>.font(.title)</pre><p>Both Text views get .font(.title) because font is an <strong>environment modifier</strong>.</p><p>Contrast with:</p><pre>VStack {<br>    Text(&quot;Hello&quot;)<br>        .font(.title)<br>    Text(&quot;World&quot;)<br>}</pre><p>Only “Hello” will be .title, while “World” uses a default font.</p><p>Other common environment-style modifiers:</p><ul><li>.foregroundColor(_:) on a container</li><li>.accentColor(_:) (older API; newer is tint)</li><li>.tint(_:)</li><li>.environment(\.locale, ...)</li><li>.environmentObject(_:)</li></ul><blockquote><em>Rule of thumb: If a modifier applies to many children, consider moving it </em><strong><em>up</em></strong><em> to their parent view.</em></blockquote><p>This keeps your code DRY and easier to maintain.</p><h3>5. Conditional Modifiers (Cleanly)</h3><p>Very often you want:</p><blockquote><em>“Apply this modifier only if some condition is true.”</em></blockquote><p>Naive version:</p><pre>if isSelected {<br>    Text(&quot;Item&quot;)<br>        .foregroundColor(.blue)<br>} else {<br>    Text(&quot;Item&quot;)<br>        .foregroundColor(.gray)<br>}</pre><p>This works, but you’re duplicating the base view.</p><h3>5.1 Using if inside the chain</h3><pre>Text(&quot;Item&quot;)<br>    .foregroundColor(isSelected ? .blue : .gray)</pre><p>Or for more complex cases:</p><pre>Text(&quot;Item&quot;)<br>    .padding()<br>    .background(<br>        isSelected ? Color.blue.opacity(0.2) : Color.clear<br>    )</pre><h3>5.2 Using a helper view extension (advanced but clean)</h3><p>You can define:</p><pre>extension View {<br>    @ViewBuilder<br>    func `if`&lt;Content: View&gt;(_ condition: Bool,<br>                             transform: (Self) -&gt; Content) -&gt; some View {<br>        if condition {<br>            transform(self)<br>        } else {<br>            self<br>        }<br>    }<br>}</pre><p>Now you can write:</p><pre>Text(&quot;Item&quot;)<br>    .padding()<br>    .if(isSelected) { view in<br>        view<br>            .background(Color.blue.opacity(0.2))<br>            .cornerRadius(8)<br>    }</pre><p>This feels very “SwiftUI-ish” and keeps a single base view.</p><h3>6. Creating Custom Modifiers (ViewModifier)</h3><p>When you see the <strong>same chain of modifiers</strong> multiple times, it’s time for a <strong>custom modifier</strong>.</p><p>Let’s say you keep writing:</p><pre>Text(&quot;Primary&quot;)<br>    .font(.headline)<br>    .foregroundColor(.white)<br>    .padding(.horizontal, 16)<br>    .padding(.vertical, 8)<br>    .background(Color.blue)<br>    .cornerRadius(10)</pre><h3>6.1 Define a ViewModifier</h3><pre>struct PrimaryButtonStyle: ViewModifier {<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .font(.headline)<br>            .foregroundColor(.white)<br>            .padding(.horizontal, 16)<br>            .padding(.vertical, 8)<br>            .background(Color.blue)<br>            .cornerRadius(10)<br>    }<br>}</pre><h3>6.2 Create a View extension for convenience</h3><pre>extension View {<br>    func primaryButtonStyle() -&gt; some View {<br>        self.modifier(PrimaryButtonStyle())<br>    }<br>}</pre><h3>6.3 Use it everywhere</h3><pre>Button(&quot;Save&quot;) { /* action */ }<br>    .primaryButtonStyle()<br><br>Button(&quot;Delete&quot;) { /* action */ }<br>    .primaryButtonStyle()</pre><p>You just created your own <strong>custom modifier</strong>, just like any built-in modifier.</p><h3>7. Custom Modifiers with Parameters</h3><p>You can make modifiers configurable:</p><pre>struct CapsuleTag: ViewModifier {<br>    let background: Color<br><br>func body(content: Content) -&gt; some View {<br>        content<br>            .font(.caption)<br>            .foregroundColor(.white)<br>            .padding(.horizontal, 10)<br>            .padding(.vertical, 4)<br>            .background(background)<br>            .clipShape(Capsule())<br>    }<br>}<br>extension View {<br>    func capsuleTag(background: Color = .blue) -&gt; some View {<br>        self.modifier(CapsuleTag(background: background))<br>    }<br>}</pre><p>Usage:</p><pre>Text(&quot;SwiftUI&quot;)<br>    .capsuleTag(background: .green)<br><br>Text(&quot;iOS&quot;)<br>    .capsuleTag()    // uses default .blue</pre><p>This is powerful for building a <strong>design system</strong> inside your app.</p><h3>8. Composing Complex UIs with Modifiers</h3><p>Modifiers shine when you start <strong>composing</strong> them.</p><p>Take something like a “card” view:</p><pre>extension View {<br>    func cardStyle() -&gt; some View {<br>        self<br>            .padding()<br>            .background(<br>                RoundedRectangle(cornerRadius: 16)<br>                    .fill(Color(.systemBackground))<br>                    .shadow(radius: 4)<br>            )<br>            .padding(.horizontal)<br>    }<br>}</pre><p>Use it like:</p><pre>VStack(alignment: .leading, spacing: 8) {<br>    Text(&quot;John Doe&quot;)<br>        .font(.headline)<br>    Text(&quot;iOS Developer&quot;)<br>        .font(.subheadline)<br>        .foregroundColor(.secondary)<br>}<br>.cardStyle()</pre><p>By encapsulating your common style patterns into modifiers, you:</p><ul><li>Keep views <strong>smaller and more readable</strong></li><li>Ensure <strong>consistent design</strong></li><li>Make it easy to adjust style in <strong>one place</strong> later</li></ul><h3>9. Common Mistakes &amp; How to Avoid Them</h3><p>Let’s look at some classic modifier mistakes.</p><h3>9.1 Too Many Modifiers Inline</h3><p>This quickly becomes unreadable:</p><pre>Text(&quot;Hello, this is a very long text&quot;)<br>    .font(.system(size: 16, weight: .medium, design: .rounded))<br>    .foregroundColor(.white)<br>    .padding(.horizontal, 24)<br>    .padding(.vertical, 12)<br>    .background(Color.blue)<br>    .cornerRadius(12)<br>    .shadow(radius: 6)<br>    .padding(.top, 20)</pre><p><strong>Fix:</strong> extract a custom modifier or view:</p><pre>Text(&quot;Hello, this is a very long text&quot;)<br>    .primaryCardTextStyle()</pre><h3>9.2 Ignoring Modifier Order</h3><p>If your layout or styling looks off, always ask:</p><blockquote><em>“Is my modifier order doing what I think it is?”</em></blockquote><p>Try swapping .padding, .background, .frame, etc., and see the difference.</p><h3>9.3 Overusing Fixed Sizes</h3><pre>Text(&quot;Label&quot;)<br>    .frame(width: 200, height: 50)</pre><p>This might break on smaller devices, larger text sizes, or different languages.</p><p><strong>Prefer</strong> flexible layout: padding, Spacer, stacks, frame(maxWidth: .infinity, alignment: ...) where appropriate.</p><h3>10. Mental Model: Views as Data, Modifiers as Transformers</h3><p>To think like SwiftUI:</p><ul><li><strong>Views</strong> = <em>declarative descriptions</em> of what you want</li><li><strong>Modifiers</strong> = <em>pure functions</em> transforming one view description into another</li><li><strong>SwiftUI engine</strong> = reads your tree and decides how to render &amp; update it</li></ul><p>You’re not telling SwiftUI <em>how</em> to draw pixel-by-pixel; you’re telling it:</p><blockquote><em>“Start with this view, then apply these transformations in this order.”</em></blockquote><p>Once you internalize that, modifiers stop being “magic syntax” and start feeling like a very clean functional pipeline.</p><h3>11. Putting It All Together: Example</h3><p>Here’s a small but realistic example that combines multiple ideas:</p><pre>import SwiftUI<br><br>struct UserCard: View {<br>    let name: String<br>    let role: String<br>    let isOnline: Bool<br>    var body: some View {<br>        HStack(spacing: 12) {<br>            Circle()<br>                .fill(isOnline ? Color.green : Color.gray)<br>                .frame(width: 12, height: 12)<br>            VStack(alignment: .leading, spacing: 4) {<br>                Text(name)<br>                    .font(.headline)<br>                Text(role)<br>                    .font(.subheadline)<br>                    .foregroundColor(.secondary)<br>            }<br>            Spacer()<br>        }<br>        .padding()<br>        .cardStyle()                          // custom modifier<br>        .accessibilityElement(children: .combine)<br>        .accessibilityLabel(&quot;\(name), \(role), \(isOnline ? &quot;online&quot; : &quot;offline&quot;)&quot;)<br>    }<br>}</pre><p>We used:</p><ul><li>Layout (HStack, VStack, padding, Spacer)</li><li>Style modifiers (font, foregroundColor, background via cardStyle)</li><li>Custom modifier (cardStyle())</li><li>Conditional styling (isOnline ? Color.green : Color.gray)</li><li>Accessibility modifiers</li></ul><p>This is what “expert-level” SwiftUI often looks like: not very complicated syntax, but <strong>thoughtful composition of modifiers</strong>.</p><h3>12. Final Tips for Mastering Modifiers</h3><ul><li><strong>Read the docs</strong> of common modifiers like padding, frame, background, overlay, clipShape — tiny details matter.</li><li>When something breaks, <strong>simplify</strong>: comment out modifiers and add them back one by one.</li><li>Extract <strong>custom modifiers</strong> early. If you repeated a chain twice, it’s probably time.</li><li>Use environment modifiers (.font, .foregroundColor, .tint) at the container level for consistent styling.</li><li>Always remember: <strong>order matters</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d950188434e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Identifiable & Hashable in Swift & SwiftUI: Why They Matter]]></title>
            <link>https://scripturesintech.medium.com/mastering-identifiable-hashable-in-swift-swiftui-why-they-matter-6dd45c6e2d3e?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dd45c6e2d3e</guid>
            <category><![CDATA[identifiable]]></category>
            <category><![CDATA[hashable-protocol]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 06:36:20 GMT</pubDate>
            <atom:updated>2025-12-08T06:36:20.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZ1JByTs953tclmdI6Lz_Q.png" /></figure><p>Swift and SwiftUI provide powerful language features that help developers manage state, track data changes, and build efficient UI. Among these are two foundational protocols:</p><ul><li>Identifiable</li><li>Hashable</li></ul><p>They may look simple at first glance, but using them correctly resolves several critical challenges in UI identity, data validation, performance, and correctness.</p><p>In this article, we break down <strong>what they are</strong>, <strong>how they work internally</strong>, <strong>why SwiftUI depends on them</strong>, and <strong>what goes wrong without them</strong>.</p><h3>🔹 Why Do We Need Identity in SwiftUI?</h3><p>SwiftUI is <strong>state-driven</strong>.<br> When data changes, SwiftUI needs to understand:</p><ul><li>Which item was changed?</li><li>Which item should be removed from the UI?</li><li>Which view should animate or update?</li></ul><p>Without identity, SwiftUI would not know <strong>what to redraw</strong> — resulting in improper UI updates.</p><p>Example scenario:</p><pre>List(users) { user in<br>    Text(user.name)<br>}</pre><p>How does SwiftUI know which row is which when a user’s name updates?<br> 👉 Because the model conforms to Identifiable.</p><h3>🔑 Understanding Identifiable</h3><h3>What It Is</h3><p>A protocol that assigns <strong>a unique and stable identity</strong> to a data model.</p><pre>public protocol Identifiable {<br>    associatedtype ID : Hashable<br>    var id: Self.ID { get }<br>}</pre><p><strong>Key takeaways:</strong></p><ul><li>id must be <em>unique</em> and <em>constant</em> for that instance</li><li>ID itself must be Hashable</li><li>Used for UI element differentiation</li></ul><h3>Internal Usage</h3><p>SwiftUI internally performs diffing on lists using the id.<br> It evaluates:</p><ul><li>Which elements are new?</li><li>Which are updated?</li><li>Which are deleted or moved?</li></ul><p>This fuels animations and efficient rendering.</p><h3>Example</h3><pre>struct User: Identifiable {<br>    let id = UUID()<br>    let name: String<br>}</pre><p>Now SwiftUI always knows:<br> ➡️ “This User is still the same user even if the name changes.&quot;</p><h3>❌ Problem Without Identifiable</h3><pre>struct User { let name: String }<br><br>List(users) { user in<br>    Text(user.name)<br>}</pre><p>SwiftUI will complain:</p><blockquote><em>Initializer requires explicit id value because </em><em>User has no identity.</em></blockquote><p>Workaround:</p><pre>List(users, id: \.name) { user in<br>    Text(user.name)<br>}</pre><p>But this is risky!<br> If two users share the same name → UI breaks ⚠️</p><p>Hence → <strong>Stable identity matters</strong>.</p><h3>🔁 Understanding Hashable</h3><h3>What It Is</h3><p>A protocol allowing values to be:</p><ul><li>Compared efficiently</li><li>Used in Set, dictionary keys, diffing algorithms</li></ul><pre>public protocol Hashable : Equatable {<br>    func hash(into hasher: inout Hasher)<br>}</pre><p>Swift automatically synthesizes hashing for struct properties.</p><h3>Example</h3><pre>struct Car: Hashable {<br>    let model: String<br>    let year: Int<br>}<br><br>let set: Set&lt;Car&gt; = [<br>    Car(model: &quot;Tesla&quot;, year: 2023),<br>    Car(model: &quot;Tesla&quot;, year: 2023) // duplicate removed<br>]</pre><p>Because both properties match → both cars <em>are equal</em>.</p><h3>Internal Use</h3><p>SwiftUI often uses hashing when comparing data updates inside a List, ForEach, and animations.</p><h3>🧩 Where Hashable &amp; Identifiable Work Together</h3><p>When using data in SwiftUI, you commonly need both:</p><pre>struct Todo: Identifiable, Hashable {<br>    let id = UUID()<br>    var title: String<br>}</pre><p>Why both?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MfFap09Po0MHmMV8lo5DQ.png" /></figure><p>➡️ <strong>Identifiable guarantees uniqueness for UI</strong><br> ➡️ <strong>Hashable ensures proper equality for data processing</strong></p><h3>⚠️ Issues Without Hashable in SwiftUI</h3><p>Some SwiftUI modifiers and patterns require hashing:</p><ul><li>List with .onDelete</li><li>View selection tracking</li><li>Animatable comparisons</li></ul><p>Example:</p><pre>@State private var selectedCar: Car? // Car must be Hashable</pre><p>Otherwise Swift cannot verify equality → selection becomes broken.</p><h3>🎯 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NP2nyFHYFExvkC7ZwRyfA.png" /></figure><h3>🚀 Final Thoughts</h3><p>SwiftUI updates UIs based on data identity.<br> If identity is ambiguous → performance drops or views crash.</p><p>✔ Always use <strong>Identifiable</strong> for models displayed in UI<br> ✔ Use <strong>Hashable</strong> when value comparison or set membership matters<br> ✔ Combine both for strong, safe data models</p><p>Once understood, these two small protocols provide huge clarity — making your SwiftUI apps more robust, efficient, and elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dd45c6e2d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Scalable SwiftUI App with Coordinator Pattern, Observation Framework, and Clean…]]></title>
            <link>https://scripturesintech.medium.com/building-a-scalable-swiftui-app-with-coordinator-pattern-observation-framework-and-clean-750b0edfbce9?source=rss-b8781e45b90c------2</link>
            <guid isPermaLink="false">https://medium.com/p/750b0edfbce9</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[coordinator-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Roopesh Tripathi]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 17:12:35 GMT</pubDate>
            <atom:updated>2025-12-08T05:48:31.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Building a Scalable SwiftUI App with Coordinator Pattern, Observation Framework, and Clean Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd7GzIZiSUpL2W72TbpB9Q.png" /></figure><p>Modern iOS apps require much more than a simple navigation stack.<br> Apps grow quickly → you get:</p><ul><li>Multiple navigation flows</li><li>Sheets, full-screen modals, alerts</li><li>Feature-specific navigation logic</li><li>Reusable components</li><li>Testable presentation logic</li></ul><p>Sadly… SwiftUI’s built-in NavigationStack alone <strong>does not scale</strong>.</p><p>So in this blog, we’ll build a <strong>full-blown coordinator framework</strong> designed to scale with real-world apps:</p><p>✔ <strong>Coordinator Pattern</strong> — Feature-based routing &amp; composition<br> ✔ <strong>Clean Architecture</strong> — Separation of concerns<br> ✔ <strong>SOLID principles</strong> — Testable, maintainable<br> ✔ <strong>Observation Framework (@Observable + @Bindable)</strong> — Modern state management<br> ✔ Supporting:</p><ul><li>Navigation push/pop stack</li><li>Multiple independent flows</li><li>Modals (sheet / fullScreenCover)</li><li>Global alert handling</li></ul><p>📌 <strong>No Combine + No legacy ObservableObject required</strong><br> We use Apple’s new <strong>Observation framework</strong> (iOS 17+)</p><h3>🧩 Why Coordinator + Clean Architecture?</h3><h3>Without Coordinator:</h3><p>❌ Views create other views<br> ❌ Features become tightly coupled<br> ❌ Business logic leaks into UI<br> ❌ Deep navigation stack becomes unmanageable<br> ❌ Hard to test</p><h3>With Coordinator:</h3><p>✔ Navigation is <strong>abstracted</strong><br> ✔ Features operate independently<br> ✔ Reusable flows (Auth, Settings, Users)<br> ✔ Unit test navigation <strong>without UI</strong><br> ✔ Better team scaling</p><h3>🏛 Architecture Overview</h3><p>We split responsibilities:</p><p>LayerRoleSample TypesPresentationUI + Navigation + ViewModelCoordinator, Router, SwiftUI ViewsDomainBusiness RulesUseCase, Entity, ProtocolsDataNetworking + CacheRepository, DTO, API Client</p><p>Navigation belongs fully to <strong>Presentation</strong> layer.</p><h3>🧠 High-Level Navigation Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKx4O3RK9wXOGbB4fPhlTQ.png" /></figure><pre><br>// courtesy: https://mermaid.js.org/<br><br>flowchart LR<br>    App --&gt; NavigationStack<br>    NavigationStack --&gt; AppRouter<br>    AppRouter --&gt; AppCoordinator<br>    AppCoordinator --&gt; FeatureViews<br>    FeatureViews --&gt; AppRouter</pre><p>UI → Router → Coordinator → View → back to Router.<br> Everyone knows exactly <strong>what</strong> they own.</p><h3>🎬 Core: Router + Coordinator Framework</h3><h3>🧱 Define all routes</h3><pre>// MARK: - AppScreen.swift</pre><pre>public enum AppScreen: Hashable, Identifiable {<br>    case usersList<br>    case userDetails(id: Int)<br>    case settings<br>    case about<br>    case web(url: URL)</pre><pre>public var id: String {<br>        switch self {<br>        case .usersList:               return &quot;usersList&quot;<br>        case .userDetails(let id):     return &quot;userDetails_\(id)&quot;<br>        case .settings:                return &quot;settings&quot;<br>        case .about:                   return &quot;about&quot;<br>        case .web(let url):            return &quot;web_\(url.absoluteString)&quot;<br>        }<br>    }<br>}</pre><blockquote><em>In large teams → split per feature: </em><em>UsersScreen, </em><em>SettingsScreen, etc.</em></blockquote><h3>🚦 Navigation State &amp; UI triggers</h3><pre>// MARK: - AppRouter.swift</pre><pre><a href="http://twitter.com/Observable">@Observable</a><br>public final class AppRouter&lt;Screen: Hashable &amp; Identifiable&gt; {<br>    public var path = NavigationPath()</pre><pre>public var sheet: Screen?<br>    public var fullScreenCover: Screen?<br>    public var alert: AlertConfig?</pre><pre>public func push(_ screen: Screen) { path.append(screen) }</pre><pre>public func pop() { path.removeLast() }</pre><pre>public func setRoot(_ screen: Screen) { <br>   path = NavigationPath();<br>   push(screen) <br>}</pre><pre>public func presentSheet(_ screen: Screen) { sheet = screen }</pre><pre>public func presentFullScreen(_ screen: Screen) { <br>   fullScreenCover = screen <br>}</pre><pre>public func showAlert(_ config: AlertConfig) { alert = config }</pre><pre>}</pre><p>This is our <strong>single source of truth</strong> for navigation.</p><h3>🎭 Coordinators: “View Factory per Screen”</h3><pre>// MARK: - Coordinator.swift</pre><pre>public protocol Coordinator {<br>    associatedtype Screen: Hashable &amp; Identifiable<br>    associatedtype RootView: View<br>    <br>    var router: AppRouter&lt;Screen&gt; { get }<br>    <a href="http://twitter.com/ViewBuilder">@ViewBuilder</a> func view(for screen: Screen) -&gt; RootView<br>}</pre><h3>🎯 AppCoordinator — Main navigation orchestrator</h3><p>Responsibility:</p><ul><li>Build feature screens</li><li>Inject dependencies</li></ul><pre>// MARK: - AppCoordinator.swift</pre><pre><a href="http://twitter.com/MainActor">@MainActor</a><br>public final class AppCoordinator: Coordinator {<br>    <br>    public typealias Screen = AppScreen<br>    public typealias RootView = AnyView</pre><pre>public let router: AppRouter&lt;AppScreen&gt;<br>    private let usersViewModelFactory: () -&gt; UsersViewModel<br>    <br>    public init(router: AppRouter&lt;AppScreen&gt;,<br>                usersViewModelFactory: <a href="http://twitter.com/escaping">@escaping</a> () -&gt; UsersViewModel) {<br>        self.router = router<br>        self.usersViewModelFactory = usersViewModelFactory<br>    }</pre><pre><a href="http://twitter.com/ViewBuilder">@ViewBuilder</a><br>    public func view(for screen: AppScreen) -&gt; AnyView {<br>        switch screen {<br>        case .usersList:<br>            AnyView(UserListView(<br>                viewModel: usersViewModelFactory(),<br>                appRouter: router<br>            ))<br>            <br>        case .userDetails(let id):<br>            AnyView(UserDetailsView(userId: id, appRouter: router))<br>            <br>        case .settings:<br>            AnyView(SettingsView(appRouter: router))<br>            <br>        case .about:<br>            AnyView(AboutView(appRouter: router))<br>            <br>        case .web(let url):<br>            AnyView(WebViewScreen(url: url, appRouter: router))<br>        }<br>    }<br>}</pre><h3>🧩 RootView connects Router ↔ NavigationStack</h3><pre>// MARK: - RootView.swift</pre><pre><a href="http://twitter.com/MainActor">@MainActor</a><br>struct RootView: View {<br>    <a href="http://twitter.com/Bindable">@Bindable</a> var router: AppRouter&lt;AppScreen&gt;<br>    private let coordinator: AppCoordinator</pre><pre>var body: some View {<br>        NavigationStack(path: $router.path) {<br>            coordinator.view(for: .usersList)<br>                .navigationDestination(for: AppScreen.self) { <br>                    screen in<br>                    coordinator.view(for: screen)<br>                }<br>                .sheet(item: $router.sheet, content: coordinator.view)<br>                .fullScreenCover(item: $router.fullScreenCover, content: coordinator.view)<br>                .alert(item: $router.alert) { $0.toSwiftUIAlert() }<br>        }<br>        .onAppear {<br>            if router.path.isEmpty { router.setRoot(.usersList) }<br>        }<br>    }<br>}</pre><h3>🎥 Feature Navigation Example (Users Flow)</h3><h3>1️⃣ User list screen (with infinite scroll)</h3><pre>// MARK: - UserListView.swift</pre><pre><a href="http://twitter.com/MainActor">@MainActor</a><br>struct UserListView: View {<br>    <a href="http://twitter.com/Bindable">@Bindable</a> var viewModel: UsersViewModel<br>    let appRouter: AppRouter&lt;AppScreen&gt;</pre><pre>var body: some View {<br>        List {<br>            ForEach(viewModel.users) { user in<br>                Button {<br>                    appRouter.push(.userDetails(id: user.id))<br>                } label: {<br>                    UserRowView(user: user)<br>                }<br>                .onAppear {<br>                    Task { await viewModel.loadMoreIfNeeded(currentItem: user) }<br>                }<br>            }<br>        }<br>        .task { await viewModel.loadInitial() }<br>        .navigationTitle(&quot;Users&quot;)<br>        .toolbar {<br>            ToolbarItem(placement: .navigationBarTrailing) {<br>                Button { appRouter.presentSheet(.settings) } label: {<br>                    Image(systemName: &quot;gear&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>2️⃣ Details screen</h3><pre><a href="http://twitter.com/MainActor">@MainActor</a><br>struct UserDetailsView: View {<br>    let userId: Int<br>    let appRouter: AppRouter&lt;AppScreen&gt;</pre><pre>var body: some View {<br>        VStack {<br>            Text(&quot;User ID: \(userId)&quot;)<br>            Button(&quot;Open Web&quot;) {<br>                appRouter.push(.web(url: URL(string: &quot;<a href="https://example.com/">https://example.com</a>&quot;)!))<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><h3>🔗 App Entry — Child Coordinators Ready</h3><pre>// MARK: - UsersApp.swift</pre><pre><a href="http://twitter.com/main">@main</a><br>struct UsersApp: App {<br>    <a href="http://twitter.com/State">@State</a> private var router = AppRouter&lt;AppScreen&gt;()<br>    <a href="http://twitter.com/State">@State</a> private var coordinator: AppCoordinator</pre><pre>init() {<br>        let httpClient = URLSessionHTTPClient()<br>        let userAPI = UserAPI()<br>        let localStore = CoreDataUserLocalDataSource(container: .init(name: &quot;UsersModel&quot;))<br>        let repository = UserRepository(httpClient: httpClient,<br>                                        userAPI: userAPI,<br>                                        localDataSource: localStore)<br>        let useCase = FetchUsersPageUseCase(repository: repository)</pre><pre>let usersFactory = {<br>            UsersViewModel(fetchUsersPageUseCase: useCase,<br>                           analytics: ConsoleAnalyticsLogger())<br>        }</pre><pre>let router = AppRouter&lt;AppScreen&gt;()<br>        _router = State(initialValue: router)<br>        _coordinator = State(initialValue: AppCoordinator(<br>            router: router,<br>            usersViewModelFactory: usersFactory<br>        ))<br>    }</pre><pre>var body: some Scene {<br>        WindowGroup {<br>            RootView(router: router, coordinator: coordinator)<br>        }<br>    }<br>}</pre><h3>📊 Coordinator + Router Class Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zow77i1bqiNIleEWAyICnw.png" /></figure><pre><br>// <strong>courtesy</strong>: <a href="https://mermaid.js.org/">https://mermaid.js.org/</a><br>classDiagram<br>    class AppRouter~Screen~ {<br>        +path: NavigationPath<br>        +sheet: Screen?<br>        +fullScreenCover: Screen?<br>        +alert: AlertConfig?<br>        +push(Screen)<br>        +pop()<br>        +setRoot(Screen)<br>        +presentSheet(Screen)<br>        +presentFullScreen(Screen)<br>        +showAlert(AlertConfig)<br>    }<br><br>    class Coordinator {<br>        &lt;&lt;protocol&gt;&gt;<br>        +router: AppRouter<br>        +view(for: Screen)<br>    }<br><br>    class AppCoordinator {<br>        +router<br>        +view(for:)<br>    }<br><br>    AppCoordinator ..|&gt; Coordinator<br>    AppCoordinator --&gt; AppRoutermer</pre><h3>🧪 Testability ❤️</h3><p>With Coordinator:</p><pre>final class RouterSpy: AppRouter&lt;AppScreen&gt; {<br>    var pushed: [AppScreen] = []<br>    override func push(_ screen: AppScreen) {<br>        pushed.append(screen)<br>        super.push(screen)<br>    }<br>}</pre><p>Test navigation <strong>without running UI</strong> ✔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750b0edfbce9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>