<?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 Mukund Jogi on Medium]]></title>
        <description><![CDATA[Stories by Mukund Jogi on Medium]]></description>
        <link>https://medium.com/@mukundjogi?source=rss-ea5224204e53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9FE-BgByJg0ZkszvIJkWOQ.jpeg</url>
            <title>Stories by Mukund Jogi on Medium</title>
            <link>https://medium.com/@mukundjogi?source=rss-ea5224204e53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:10:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mukundjogi/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[Instagram scrolling and the science of Dopamine]]></title>
            <link>https://medium.com/@mukundjogi/instagram-scrolling-and-the-science-of-dopamine-27f90c4e0b4d?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/27f90c4e0b4d</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 08:57:34 GMT</pubDate>
            <atom:updated>2026-01-23T08:57:34.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joADIyERoBnzrGOAlw2-_Q.png" /></figure><p>You didn’t plan to scroll this long.</p><p>You opened Instagram for <em>one thing</em>.<br>One message.<br>One notification.</p><p>But your thumb kept moving.<br>One Reel.<br>Another.<br>Another.</p><p>No lag.<br>No loading.<br>No reason to stop.</p><p>That smooth, endless scrolling experience isn’t luck.<br>It’s the result of <strong>deep mobile engineering + behavioral psychology</strong>, carefully tuned across <strong>Android, iOS, Flutter, and React Native</strong>.</p><p>Let’s break down <strong>what’s really happening behind the scenes</strong> from your screen… all the way to dopamine in your brain.</p><h3>One swipe doesn’t scroll — It triggers a reward</h3><p>Instagram Reels isn’t a free-scroll feed.</p><p>Each swipe lands on <strong>exactly one full-screen video</strong>.</p><p>Across platforms, this is implemented using:</p><ul><li><strong>Android</strong> → ViewPager2 / RecyclerView with snapping</li><li><strong>iOS</strong> →<br><strong>UIKit</strong> → UICollectionView with paging<br><strong>SwiftUI</strong> → ScrollView + LazyVStack + .scrollTargetBehavior(.paging)</li><li><strong>Flutter</strong> → PageView.builder</li><li><strong>React Native</strong> → FlatList with pagingEnabled</li></ul><h3>Why this matters psychologically</h3><p>Your brain loves <strong>clean cause → effect loops</strong>.</p><p>One swipe<br>→ One new Reel<br>→ One potential reward</p><p>No half states.<br>No ambiguity.</p><p>That predictability creates a tiny hit of satisfaction every time.</p><h3>Why reels start Instantly (And why that’s critical)</h3><p>Dopamine isn’t released by pleasure alone.</p><p>It’s released by <strong>anticipation</strong>.</p><p>Instagram aggressively protects that moment.</p><p>Behind the scenes:</p><ul><li><strong>Android</strong> → ExoPlayer pre-buffering</li><li><strong>iOS</strong> → AVPlayer background buffering</li><li><strong>Flutter</strong> → Video controllers initialized early</li><li><strong>React Native</strong> → Native video modules handle buffering</li></ul><p>While you watch one Reel, the next one is already waiting.</p><p>No spinner.<br>No delay.<br>No disappointment.</p><p>That uninterrupted anticipation keeps your brain engaged.</p><h3>The real hook: The variable reward system</h3><p>Not every Reel is amazing.</p><p>Some are average.<br>Some you skip instantly.<br>Then suddenly <strong>one you love</strong>.</p><p>That unpredictability is intentional.</p><p>Psychology calls this a <strong>variable reward schedule</strong> the same mechanism used in:</p><ul><li>Slot machines</li><li>Games</li><li>Notifications</li></ul><p>Instagram carefully mixes:</p><ul><li>High-engagement content</li><li>Neutral fillers</li><li>Occasionally “perfect” Reels</li></ul><p>You don’t scroll for the current video.<br>You scroll for the <em>possibility</em> of the next great one.</p><p>That possibility releases dopamine.</p><h3>How Instagram prefetches Reels before you even reach them</h3><p>This is where engineering really shines.</p><p>Instagram doesn’t wait for you to swipe.<br>It <strong>assumes you will</strong>.</p><h3>The core idea</h3><ul><li>Prefetch <strong>1–2 Reels ahead</strong></li><li>Buffer only the <strong>first few seconds</strong></li><li>Cancel or downgrade downloads instantly if behavior changes</li></ul><h3>The prefetch window (Conceptually)</h3><pre>Previous Reel → Cached or released<br>Current Reel  → Fully buffered<br>Next Reel     → Partially buffered (1–3 seconds)<br>Next +1       → Metadata + thumbnail only</pre><p>This window slides continuously as you scroll.</p><h3>How Instagram decides what to prefetch</h3><p>It predicts:</p><ul><li>Scroll direction (almost always downward)</li><li>Scroll speed</li><li>Pause behavior</li></ul><p>If you scroll slowly → prefetch more<br>If you flick fast → prefetch lighter, lower quality<br>If you pause → upgrade buffer quality immediately</p><h3>Platform-Wise Prefetching</h3><h4>Android</h4><ul><li>ExoPlayer pre-buffer APIs</li><li>Disk + memory caching layers</li><li>Background threads only</li><li>Triggered via scroll listeners</li></ul><p>Conceptually:</p><pre>if (scrollSpeed &lt; threshold) {<br>    prefetch(nextVideo, highPriority)<br>} else {<br>    prefetch(nextVideo, lowPriority)<br>}</pre><h4>iOS</h4><ul><li>AVPlayerItem prepared in advance</li><li>Background buffering with smart eviction</li><li>Hardware decoding</li><li>Aggressive memory pressure handling</li></ul><p>Older buffers are dropped instantly if memory tightens.</p><h4>Flutter</h4><ul><li>Uses native video players internally</li><li>Controllers initialized early</li><li>Prefetch logic handled via platform channels</li><li>Dart UI stays lightweight and responsive</li></ul><h4>React Native</h4><ul><li>JS predicts scroll behavior</li><li>Native modules handle buffering &amp; caching</li><li>UI thread stays independent of JS thread</li></ul><p>This avoids scroll lag even on slower devices.</p><h3>Why Instagram prefetches Just Enough</h3><p>Over-prefetching causes:</p><ul><li>Battery drain</li><li>Network waste</li><li>Crashes on low-end phones</li></ul><p>So limits are:</p><ul><li>Device-aware</li><li>Network-aware (Wi-Fi vs mobile data)</li><li>Dynamic based on behavior</li></ul><p>The goal is balance:<br><strong>Speed vs Memory vs Battery vs Network</strong></p><h3>Every scroll Is teaching the Algorithm about you</h3><p>Instagram doesn’t rely on likes alone.</p><p>It watches:</p><ul><li>How fast you scroll</li><li>Where you pause</li><li>Replays</li><li>How quickly you swipe away</li></ul><p>Captured via:</p><ul><li><strong>Android</strong> → Scroll listeners</li><li><strong>iOS</strong> → Gesture recognizers</li><li><strong>Flutter</strong> → ScrollNotification</li><li><strong>React Native</strong> → Touch &amp; scroll events</li></ul><p>Each micro-interaction refines what comes next.</p><p>That’s why you often think:</p><blockquote><em>“How did it know I’d like this?”</em></blockquote><p>Feeling understood triggers dopamine.</p><h3>Why scrolling never feels laggy</h3><p>Lag kills immersion.</p><p>Even a 200ms stutter breaks the emotional loop.</p><p>So Instagram reuses views aggressively:</p><ul><li><strong>Android</strong> → RecyclerView.ViewHolder</li><li><strong>iOS</strong> → Cell reuse</li><li><strong>Flutter</strong> → Render object recycling</li><li><strong>React Native</strong> → Native view reuse</li></ul><p>The screen stays the same.<br>Only the content changes.</p><p>Your brain perceives this as <em>effortless</em>.</p><h3>UI threads are protected at all costs</h3><p>Smooth scrolling depends on one rule:<br><strong>Never block the UI thread.</strong></p><ul><li>Android offloads work from the main thread</li><li>iOS keeps the run loop clean</li><li>Flutter uses isolates</li><li>React Native lets native UI run independently</li></ul><p>Psychologically:<br><strong><em>No lag → no frustration<br>No frustration → no exit impulse</em></strong></p><p>So you keep scrolling.</p><h3>Why there’s no “You’re Done” message</h3><p>Reels never says:</p><blockquote><em>“That’s all for today.”</em></blockquote><p>There’s:</p><ul><li>No footer</li><li>No page number</li><li>No stopping cue</li></ul><p>Without a natural end, your brain stays in <strong>seeking mode</strong>.</p><p>Seeking mode releases dopamine.<br>Satisfied mode makes you stop.</p><p>Instagram keeps you seeking.</p><h3>Tiny Animations, Perfect Timing</h3><p>Small animations reinforce reward timing:</p><ul><li>Snap easing</li><li>Subtle fades</li><li>Frame-perfect pacing (~16ms)</li></ul><p>Across platforms:</p><ul><li>Android interpolators</li><li>iOS Core Animation curves</li><li>Flutter implicit animations</li><li>React Native native-driven animations</li></ul><p>Your brain reads this as:</p><blockquote><em>“That felt good. Do it again.”</em></blockquote><h3>So why Can’t you Stop Scrolling?</h3><p>Because every swipe:</p><ol><li>Promises a reward</li><li>Delivers it instantly</li><li>Trains the algorithm</li><li>Improves the next reward</li></ol><p>It’s a <strong>self-reinforcing dopamine loop</strong>, powered by world-class mobile engineering.</p><p>Different platforms.<br>Same goal.</p><h3>Final thought</h3><p>Next time you think:</p><blockquote><em>“Just one more Reel…”</em></blockquote><p>Remember:<br>It’s not weak willpower.</p><p>It’s <strong>excellent software design meeting human psychology</strong>.</p><h3>Want to prepare for upcoming interviews? Here are my open-source prep repositories:</h3><p>📌 <strong>iOS Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/ios-interview">https://github.com/mukundjogi/ios-interview</a><br>📌 <strong>Android Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/android-interview">https://github.com/mukundjogi/android-interview</a><br>📌 <strong>Flutter Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/flutter-interview">https://github.com/mukundjogi/flutter-interview</a></p><p>If you find them useful, please <strong>⭐ star</strong> the repos.<br><strong>Keep sharing 🫰🏻 Keep learning 🙌🏻</strong></p><p>👏 If this post helped you see <strong>Instagram</strong> differently, <strong>clap for it</strong>, highlight a line, and share it with a developer who loves breaking apps and brains apart.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27f90c4e0b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Biometric Authentication Works Behind the Scenes]]></title>
            <link>https://medium.com/@mukundjogi/how-biometric-authentication-works-behind-the-scenes-951e5d31a81d?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/951e5d31a81d</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 04:04:20 GMT</pubDate>
            <atom:updated>2025-12-24T05:57:05.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5hUIotlmTQFo5IuLxaoLQ.png" /></figure><h3>Introduction</h3><p>You probably <strong>unlocked</strong> your phone today without <strong>thinking</strong> about it.</p><p><strong>Thumb on the sensor.</strong><br>Quick glance at the screen.<br><strong>You’re in.</strong></p><p>Biometric authentication has quietly become the default way we unlock phones, make payments, and sign into apps. It feels effortless, rest a thumb on the sensor, glance at the screen, and you’re in. But under that instant “unlock” moment, there’s a deeply engineered pipeline working to verify who you are without ever leaking who you are.</p><p>For mobile developers, this system is more than just a UX upgrade. Biometrics help reduce login friction, eliminate password fatigue, and significantly improve security if handled correctly. And because platforms like iOS and Android give us high-level APIs, it’s easy to forget how much machinery is running behind the scenes.</p><p>Let’s break it down in a clean, developer-friendly way.</p><h3>What Is Biometric Authentication?</h3><p>Biometrics rely on physical or behavioral traits that are hard to replicate. The common types include:</p><p><strong>Fingerprint</strong> — Captures ridge patterns and minutiae from your finger.<br><strong>FaceID / Face Recognition</strong> — Analyzes depth maps, contours, and facial landmarks.<br><strong>Iris Scan</strong> — Reads unique texture patterns within your iris.<br><strong>Voice Recognition</strong> — Compares vocal patterns and pitch signatures.<br><strong>Behavioral Biometrics</strong> — Tracks typing rhythm, gait analysis, touch patterns.</p><p>Each of these creates a measurable signature that can be compared against a stored template to verify identity.</p><h3>Behind-the-Scenes Flow</h3><p>Although different sensors work differently, the core flow remains consistent across modern devices.</p><h3>1. Biometric Scan</h3><p>The process starts when a user places a finger on the sensor or looks at the camera. Hardware kicks in to collect raw data.</p><h3>2. Sensor Capture</h3><p>Fingerprints are captured via capacitive or ultrasonic sensors. Faces are captured through IR depth mapping (iPhone) or camera frames plus ML models (Android).</p><h3>3. Signal Preprocessing</h3><p>Raw input is noisy. The device:</p><ul><li>Enhances contrast</li><li>Removes artifacts</li><li>Normalizes lighting and angles</li><li>Extracts points of interest (e.g., fingerprint minutiae or face landmarks)</li></ul><p>This step turns inconsistent real-world input into something machine-readable.</p><h3>4. Template Creation</h3><p>The system converts the cleaned biometric data into an encrypted mathematical representation. Not an image. Not a fingerprint picture. A one-way feature vector.</p><p>Even if someone stole this vector, they couldn’t reconstruct your face or finger from it.</p><h3>5. Template Encryption</h3><p>Before anything is stored or matched, the template is encrypted at the hardware level using device-specific keys that never leave the chip.</p><h3>6. Secure Enclave / Trusted Execution Environment (TEE)</h3><p>All sensitive operations template storage, key handling, matching occur inside a locked-down subsystem such as:</p><ul><li><strong>iOS Secure Enclave</strong></li><li><strong>Android TEE (TrustZone)</strong></li></ul><p>The main OS cannot read or inspect what happens inside these environments.</p><h3>7. Matching Engine</h3><p>When the user attempts authentication again, a fresh template is computed from the new scan and compared against the encrypted one stored inside the enclave.</p><p>The engine checks similarity scores, thresholds, and liveness signals.</p><h3>8. Match Result (Success or Fail)</h3><p>If the similarity passes the threshold, the enclave returns a “Yes” or “No” to the OS.<br>Not the data.<br>Not the template.<br>Only the decision.</p><h3>9. Fallback Conditions</h3><p>If the system can’t authenticate after a few attempts, it falls back to:</p><ul><li>PIN</li><li>Password</li><li>Pattern</li><li>Device lock screen</li></ul><p>This prevents infinite biometric attempts from any attacker.</p><h3>ASCII Flow Diagram</h3><pre>                               ┌──────────────────┐<br>                               │ User Interaction │<br>                               │ (finger/face)    │<br>                               └────────┬─────────┘<br>                                        │<br>                                        ▼<br>                            ┌──────────────────────┐<br>                            │   Sensor Captures    │<br>                            │ Raw Biometric Input  │<br>                            └───────────┬──────────┘<br>                                        │<br>                                        ▼<br>                         ┌───────────────────────────┐<br>                         │   Preprocessing Engine    │<br>                         │ Noise Cleanup + Feature   │<br>                         │ Extraction                │<br>                         └──────────────┬────────────┘<br>                                        │<br>                                        ▼<br>                         ┌────────────────────────────┐<br>                         │   Template Generation      │<br>                         │ (mathematical signature)   │<br>                         └──────────────┬─────────────┘<br>                                        │<br>                                        ▼<br>                         ┌────────────────────────────┐<br>                         │   Encryption + Secure       │<br>                         │   Storage in TEE/Enclave    │<br>                         └──────────────┬─────────────┘<br>                                        │<br>                                        ▼<br>                         ┌────────────────────────────┐<br>                         │    Matching Engine          │<br>                         │ Compare Stored vs New Temp. │<br>                         └──────────────┬─────────────┘<br>                                        │  Match / No Match<br>                                        ▼<br>                         ┌────────────────────────────┐<br>                         │  OS Receives Boolean Only  │    <br>                         └────────────────────────────┘</pre><h3>Developer Notes</h3><h3>Android: How BiometricPrompt Works</h3><p>Android’s BiometricPrompt API abstracts the entire flow:</p><ul><li>The app never sees fingerprint or face data.</li><li>All operations happen inside the TEE.</li><li>Apps only receive callbacks like onAuthenticationSucceeded().</li></ul><p>Developers should always prefer BiometricPrompt over legacy Fingerprint APIs.</p><h3>iOS: How Secure Enclave Works</h3><p>On iOS, FaceID and TouchID operations sit behind the Secure Enclave. It:</p><ul><li>Generates keys internally</li><li>Encrypts templates</li><li>Performs matching isolated from iOS</li><li>Exposes only the final decision to the app</li></ul><p>Developers usually use LocalAuthentication to integrate this flow.</p><h3>Liveness Detection</h3><p>Modern systems check whether the biometric input is real:</p><ul><li>Depth sensing for faces</li><li>Pulse detection for fingerprints</li><li>Blink detection</li><li>3D IR mapping</li></ul><p>This helps reject photos, printed fingerprints, or masks.</p><h3>Anti-Spoofing</h3><p>Devices analyze texture, heat patterns, micro-movements, and sensor inconsistencies to detect spoof attempts.</p><h3>FAR vs FRR</h3><p>Two critical metrics:</p><ul><li><strong>FAR (False Acceptance Rate)</strong>: How often a wrong person is accepted</li><li><strong>FRR (False Rejection Rate)</strong>: How often the right person is rejected</li></ul><p>Fine-tuning thresholds balances usability and security.</p><h3>Best Practices for App Developers</h3><ul><li>Never store biometric data yourself.</li><li>Use platform APIs only.</li><li>Combine biometrics with device-level encryption for sensitive actions.</li><li>Provide a fallback path for users.</li><li>Avoid custom ML models unless absolutely required.</li></ul><h3>Security Breakdown</h3><h3>Why Raw Fingerprint Data Is Never Stored</h3><p>Storing fingerprints as images would make systems permanently vulnerable. Instead, systems convert them into non-reversible templates.</p><h3>Templates vs Images</h3><p>Templates represent unique feature vectors, mathematically hashed patterns that cannot be converted back to the original biometric.</p><h3>How Encryption Works</h3><p>Templates are encrypted using keys generated and stored inside Secure Enclave or TEE. These keys are bound to the hardware and cannot be exported.</p><h3>Why Biometrics Stay On-Device</h3><p>Biometrics never leave the device because:</p><ul><li>Cloud storage is too risky</li><li>Legal frameworks restrict it</li><li>Hardware enclaves are explicitly designed for local-only operations</li></ul><p>Mobile apps simply receive a success token, not the biometric data.</p><h3>Common Failure Scenarios</h3><p>Biometrics feel instant, but they’re sensitive to environmental noise.</p><ul><li><strong>Wet fingers</strong> cause weak ridge detection.</li><li><strong>Low light</strong> affects camera-based face recognition.</li><li><strong>Dusty sensors</strong> block fingerprint signals.</li><li><strong>Mismatch due to sensor drift</strong> may occur over time.</li><li><strong>Re-enrollment needed</strong> if the user’s face changes drastically or fingerprint wears out.</li></ul><p>Devices typically request fallback authentication when these scenarios persist.</p><h3>Final Thoughts</h3><p>Biometric authentication succeeds when convenience and security work together. The system is designed so that neither the app nor the OS ever sees the raw biometric data. All sensitive logic remains locked inside hardware that is extremely difficult to tamper with.</p><p>With AI-driven liveness checks, improved depth sensors, and better spoof detection, biometrics are becoming one of the most reliable authentication layers we have. As developers, our role is simple: trust the platform, use the right APIs, and avoid reinventing the biometric pipeline.</p><h3>Want to prepare for upcoming interviews? Here are my open-source prep repositories:</h3><p>📌 <strong>iOS Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/ios-interview">https://github.com/mukundjogi/ios-interview</a><br>📌 <strong>Android Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/android-interview">https://github.com/mukundjogi/android-interview</a><br>📌 <strong>Flutter Interview Prep Repo</strong>: <a href="https://github.com/mukundjogi/flutter-interview">https://github.com/mukundjogi/flutter-interview</a></p><p>If you find them useful, please <strong>⭐ star</strong> the repos.<br><strong>Keep sharing 🫰🏻 Keep learning 🙌🏻</strong></p><p><strong>If you enjoyed this blog, keep tapping the👏 button, it really helps the story reach more developers.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951e5d31a81d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How VoIP Calling Works Behind the Scenes]]></title>
            <link>https://medium.com/@mukundjogi/how-voip-calling-works-behind-the-scenes-27c371a463c1?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c371a463c1</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[voip]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 04:05:08 GMT</pubDate>
            <atom:updated>2025-12-19T04:05:08.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAzXSo71jYYrKwp0BWRjEw.png" /><figcaption>How VoIP Calling Works Behind the Scenes</figcaption></figure><h3>1. Engaging Intro</h3><p>Voice calling feels magical. You tap a button, the other person rings, and somehow your voice travels across the world in milliseconds.</p><p>But under that simple UI lives one of the most complex, timing-sensitive engineering systems in mobile development: <strong>VoIP</strong>.</p><p>VoIP is not “just streaming audio.”<br>It’s a tight choreography of signalling, codecs, NAT traversal, jitters buffering, and real-time routing — where even a 50ms delay can destroy call quality.</p><p>This blog breaks down <strong>exactly</strong> how VoIP calling works behind the scenes — from the first tap to the final packet — using a clear, developer-oriented explanation.</p><h3>2. What This Really Means (Simple Explanation)</h3><p>Think of VoIP like sending thousands of tiny voice postcards every second.</p><p>Your microphone captures audio → chops it into micro-packets → compresses them → sends them across the internet → the receiver stitches them back together → plays them out.</p><p>But here’s the twist:<br>Your phone is usually behind Wi-Fi routers, carrier NAT, and firewalls. Voice packets can’t just travel freely. VoIP systems must “punch holes,” negotiate routes, maintain state, and ensure timing accuracy — while the user is walking, switching networks, or back-grounding the app.</p><p>At a simple level, VoIP is:</p><ol><li><strong>Signalling</strong> — “Who is calling whom?”</li><li><strong>Media negotiation</strong> — “How will we talk?”</li><li><strong>Media transport</strong> — “Send voice packets fast with no delay.”</li><li><strong>NAT traversal</strong> — “Find a way through the internet maze.”</li></ol><p>Everything else is engineering glue.</p><h3>3. The Behind-the-Scenes Breakdown</h3><p>Here’s the real internal flow of a VoIP call:</p><h3>Step 1 — App Registers with VoIP Backend</h3><p>The client shares:</p><ul><li>user ID</li><li>device ID</li><li>push token</li><li>capabilities (codecs, network type)</li></ul><h3>Step 2 — Caller Initiates a Call</h3><p>App → VoIP server:</p><pre>CallRequest {<br>  callerId: “userA”,<br>  calleeId: “userB”<br>}</pre><p>The server does <strong>signalling</strong>, not audio transport.</p><h3>Step 3 — Server Sends a Push Notification to Receiver</h3><p>This wakes the callee app from background.</p><h3>Step 4 — Receiver Accepts → Signaling Channel Opens</h3><p>Typically via WebSockets, MQTT, or SIP over WebSocket.</p><h3>Step 5 — SDP Exchange (Codec + Transport Negotiation)</h3><p>Both sides exchange capabilities:</p><ul><li>Opus, AAC, AMR-NB</li><li>RTP port</li><li>Encryption keys (SRTP)</li><li>ICE candidates (STUN/TURN servers)</li></ul><h3>Step 6 — NAT Traversal with STUN/TURN</h3><p>STUN tries to discover public IP.<br>If it fails → TURN relays media through a server.</p><h3>Step 7 — RTP Media Stream Starts</h3><p>This is the actual voice packets streaming.</p><h3>Step 8 — Jitter Buffer + Packet Repair</h3><p>Receiver smooths timing gaps and repairs packet loss.</p><h3>Step 9 — Audio Playback</h3><p>Low latency, real-time.<br>This whole flow happens in <strong>300–600 ms</strong>, ideally.</p><h3>4. Deep Technical Pipeline (With ASCII Diagram)</h3><pre>+------------------+        +----------------------+<br>|   Caller Device  |        |   Callee Device      |<br>+--------+---------+        +----------+-----------+<br>         |                           |<br>         | 1. WebSocket/SIP Register |<br>         |--------------------------&gt;|<br>         |                           |<br>         |       VoIP Backend        |<br>         +------------+--------------+<br>                      |<br>      2. CallRequest  |<br>         ------------&gt;|<br>                      |<br>                      | 3. Push Notification<br>                      +-----------------------&gt; [Callee App Wakes]<br>                      |<br>         &lt;------------+<br>      4. Accept + SDP Offer/Answer<br>                      |<br>                      |<br>      5. ICE (STUN/TURN) Negotiation<br>                      |<br>         RTP &lt;-------&gt; RTP<br>         (SRTP encrypted voice packets)</pre><h3>5. Real-World Engineering Details</h3><h3>Signalling</h3><p>Most mobile VoIP systems use:</p><ul><li><strong>SIP over WebSockets</strong></li><li><strong>Custom WebSocket signalling</strong></li><li><strong>MQTT low-latency channels</strong></li></ul><p>These carry <strong>control</strong>, not media.</p><h3>Media Layer</h3><p>RTP or SRTP transports actual audio:</p><ul><li>Opus codec is industry standard</li><li>Time-sensitive packets</li><li>No retransmissions (UDP)</li></ul><h3>Jitter Buffer</h3><p>Prevents choppy audio by:</p><ul><li>reordering packets</li><li>delaying slightly</li><li>smoothing network variance</li></ul><h3>NAT Traversal</h3><p>Real-world devices are behind:</p><ul><li>Carrier NAT</li><li>Home routers</li><li>Enterprise firewalls</li></ul><p>STUN finds public IP.<br>If impossible → TURN relays voice → slower but reliable.</p><h3>Battery Constraints</h3><p>On iOS, VoIP must use <strong>VoIP pushes</strong>.<br>On Android, foreground service is required for ongoing media.</p><h3>6. Why Things Fail (Actual Engineering Reasons)</h3><ol><li><strong>STUN blocked</strong> → media can’t connect</li><li><strong>TURN fallback too slow</strong></li><li><strong>Receiver doesn’t wake from push</strong></li><li><strong>WebSocket died silently in background</strong></li><li><strong>Jitter buffer too small</strong> → audio cracks</li><li><strong>High packet loss (Wi-Fi hopping)</strong></li><li><strong>Codec mismatch</strong></li><li><strong>SRTP key negotiation failed</strong></li><li><strong>Network switching during call</strong></li><li><strong>Aggressive OS power-saving</strong></li></ol><p>These are the real issues devs debug daily.</p><h3>7. Configurations, Keys, and Controls</h3><p>Important VoIP parameters:</p><ul><li><strong>ICE servers (STUN/TURN)</strong></li><li><strong>Codec priority</strong></li><li><strong>Max bitrate</strong></li><li><strong>DTMF mode</strong></li><li><strong>Jitter buffer min/max</strong></li><li><strong>Echo cancellation level</strong></li><li><strong>WebSocket reconnect policy</strong></li><li><strong>SRTP crypto suite</strong></li><li><strong>UDP keepalive interval</strong></li><li><strong>Call timeout, ring timeout</strong></li></ul><p>Small config changes = huge call quality differences.</p><h3>8. Practical Advice for Developers</h3><ul><li>Always keep <strong>Opus</strong> as first codec</li><li>Add an <strong>adaptive jitter buffer</strong></li><li>Use <strong>short UDP keepalives</strong> behind NAT</li><li>Log <strong>ICE candidate pairs</strong> for debugging</li><li>Implement WebSocket <strong>auto-reconnect + exponential backoff</strong></li><li>Prioritize <strong>IPv6</strong> when available</li><li>Detect and switch to <strong>TURN</strong> early when STUN stalls</li><li>Monitor packet loss every 1–2 seconds</li><li>Don’t do DSP on the main thread</li><li>Keep call UI responsive even during network stalls</li></ul><p>Real-time systems punish bad architecture quickly.</p><h3>9. Final Thoughts</h3><p>VoIP looks simple on the surface, but once you peek behind the curtain you realize it’s a beautifully engineered mess of signalling, routing, codecs, encryption, and timing tricks.</p><p>Understanding this internal pipeline won’t just help you build VoIP apps — it helps you <strong>think like a systems engineer</strong>, not just a UI developer.</p><h3>Want to prepare for upcoming interviews? Here are my open-source prep repositories:</h3><p>📌 <strong>iOS Interview Prep Repo:</strong> <a href="https://github.com/mukundjogi/ios-interview">https://github.com/mukundjogi/ios-interview</a><br>📌 <strong>Android Interview Prep Repo:</strong> <a href="https://github.com/mukundjogi/android-interview">https://github.com/mukundjogi/android-interview</a><br>📌 <strong>Flutter Interview Prep Repo:</strong> <a href="https://github.com/mukundjogi/flutter-interview">https://github.com/mukundjogi/flutter-interview</a></p><p>If you find them useful, please <strong>⭐ star</strong> the repos.</p><p><strong>Keep sharing 🫰🏻 Keep learning 🙌🏻</strong></p><p><strong>If you enjoyed this blog, tap the 👏 button — it really helps the story reach more developers.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c371a463c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Payment Gateways Work Behind the Scenes]]></title>
            <link>https://medium.com/@mukundjogi/how-payment-gateways-work-behind-the-scenes-c3093c3ad4b6?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3093c3ad4b6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 04:24:09 GMT</pubDate>
            <atom:updated>2025-12-24T07:05:31.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCuyGL_Hgw4tG0O3pAkxDQ.png" /></figure><p>When a user enters their card and taps <strong>Pay</strong>, the entire process feels instant.<br>But behind that single tap hides one of the most complex engineering pipelines in fintech.</p><p>A payment gateway doesn’t just “charge a card.”<br>It executes the digital equivalent of a global security handshake between:</p><ul><li>Your app or website</li><li>A payment gateway</li><li>Fraud systems</li><li>Card networks</li><li>Issuing banks</li><li>Acquiring banks</li><li>And finally, settlement services</li></ul><p>Most developers only see the API call.<br>But the real magic happens under the surface.</p><p>Let’s peel back the layers.</p><h3>1. What Exactly Is a Payment Gateway?</h3><p>A payment gateway is the bridge that securely moves your customer’s card information from your app → to the bank → and back with a yes/no decision.</p><p>Think of it as:</p><ul><li><strong>The translator</strong> between your app and the banking world</li><li><strong>The security guard</strong> verifying that card data isn’t stolen</li><li><strong>The courier</strong> delivering encrypted payment packets</li><li><strong>The accountant</strong> who manages captures, refunds, settlements</li></ul><p>Gateways like Stripe, Razorpay, PayPal, Braintree, and Adyen run these invisible pipelines.</p><h3>2. What Happens When a User Enters Their Card Details?</h3><p>This step looks simple in the UI.<br>But under the hood:</p><h3>Step 1 — User enters card details</h3><p>Number, expiry, CVV, name.</p><h3>Step 2 — Card details never hit your backend directly</h3><p>Modern gateways use:</p><ul><li>Hosted fields</li><li>JS SDKs</li><li>Secure iframes</li><li>Mobile native UI components</li></ul><p>This is done to maintain <strong>PCI-DSS compliance</strong>, so you never store raw card numbers.</p><h3>Step 3 — The card data is tokenized</h3><p>The gateway instantly converts the card number → a temporary <strong>token</strong>.</p><p>A token looks like this: <strong>tok_19skd92sfs82_kdjjs92j</strong></p><p>This token represents the card, but cannot be reversed to get the real number.</p><h3>Step 4 — Your server only receives the token</h3><p>This keeps your backend safe and compliant.</p><h3>🔐 3. What Happens Inside the Payment Gateway?</h3><p>Once the token reaches the gateway’s core:</p><h3>a) Risk &amp; fraud checks</h3><p>Gateways evaluate:</p><ul><li>Location mismatch</li><li>Card behavior patterns</li><li>Velocity of payments</li><li>IP reputation</li><li>Device fingerprint</li><li>BIN rules</li></ul><p>Fraud engines often decide:</p><ul><li>Approve immediately</li><li>Soft-check required (e.g., 3D Secure)</li><li>Block the transaction entirely</li></ul><h3>b) The gateway sends a request to the card network</h3><p>VISA, Mastercard, Rupay, AMEX, Diners.</p><h3>c) Card network routes it to the issuing bank</h3><p>The user’s bank verifies:</p><ul><li>CVV</li><li>PIN/OTP</li><li>Available balance</li><li>Card validity</li><li>Fraud flags</li><li>Merchant reputation</li><li>Daily limit</li></ul><h3>d) Issuer sends back “Approve” or “Decline”</h3><p>This is the “auth” result.</p><h3>4. The Behind-the-Scenes Pipeline (ASCII Diagram)</h3><p>Here’s the complete flow — clean and developer-friendly:</p><pre>                                  ┌────────────────────┐<br>                                  │       User         │<br>                                  │ Enters Card Details│<br>                                  └─────────┬──────────┘<br>                                            │ Secure Fields / SDK<br>                                            ▼<br>                              ┌──────────────────────────┐<br>                              │    Payment Gateway UI    │<br>                              │   (Tokenization Layer)   │<br>                              └────────────┬─────────────┘<br>                                           │ Creates Token<br>                                           ▼<br>                              ┌─────────────────────────┐<br>                              │     Payment Gateway     │<br>                              │  Risk + Validation Core │<br>                              └────────────┬────────────┘<br>                                           │ Sends Auth Request<br>                                           ▼<br>                               ┌──────────────────────────┐<br>                               │       Card Network       │<br>                               │ (Visa / Mastercard etc.) │<br>                               └───────────┬──────────────┘<br>                                           │ Routes Packet<br>                                           ▼<br>                               ┌────────────────────────────┐<br>                               │       Issuing Bank         │<br>                               │ Validates &amp; Approves/Denies│<br>                               └───────────┬────────────────┘<br>                                           │ Sends decision<br>                                           ▼<br>                               ┌───────────────────────────┐<br>                               │     Payment Gateway       │<br>                               │  Converts response -&gt; API │<br>                               └───────────┬───────────────┘<br>                                           │<br>                                           ▼<br>                             ┌──────────────────────────────┐<br>                             │ Merchant Backend / Checkout  │<br>                             │ Shows Paid / Failed / OTP    │<br>                             └──────────────────────────────┘</pre><h3>5. What Happens When Money Is Actually Debited?</h3><p>Important: <strong>Authorization doesn’t move money.</strong><br>It only “locks” the amount.</p><p>The actual debit happens during <strong>Capture</strong>.</p><h3>Authorization</h3><p>→ Bank checks and reserves the money.<br>→ Merchant sees “Payment Authorized”.</p><h3>Capture</h3><p>→ Merchant tells the gateway “take the money now”.<br>→ Bank transfers the reserved funds → acquiring bank.<br>→ Amount settles to the merchant after 1–3 days.</p><p>Not all gateways separate auth vs capture, but many do for:</p><ul><li>Taxis</li><li>Hotels</li><li>Food delivery</li><li>Marketplace holds</li></ul><h3>6. What Happens When the Webhook Is Fired?</h3><p>Webhooks are the gateway’s way of telling your backend:</p><ul><li>Payment authorized</li><li>Payment captured</li><li>Payment failed</li><li>Refund processed</li><li>Settlement completed</li><li>Chargeback opened</li></ul><h3>Why webhooks matter:</h3><ul><li>Your frontend cannot be trusted (network drop, tab close).</li><li>Only gateway → server communication is reliable.</li></ul><h3>A proper backend must:</h3><ul><li>Verify webhook signature</li><li>Store payment status</li><li>Update order state</li><li>Avoid double-processing</li></ul><p>This is the backbone of reliable payment systems.</p><h3>7. How Settlement Actually Works</h3><p>This part is often misunderstood.</p><h3>T+1 to T+3 days settlement</h3><p>Gateways batch all successful captures → deposit into merchant’s bank account.</p><h3>Settlement file includes:</h3><ul><li>Amount</li><li>Fees</li><li>Refunds</li><li>Chargebacks</li><li>Adjustments</li></ul><p>A good merchant dashboard shows:</p><ul><li>Captured vs unsettled</li><li>Fees</li><li>Payout timeline</li><li>Reconciliation reports</li></ul><h3>8. Why Some Payments Fail (Real Reasoning)</h3><p>Payments fail for dozens of reasons:</p><ul><li>Insufficient balance</li><li>3D Secure failure</li><li>OTP timeout</li><li>Bank server downtime</li><li>Fraud engine block</li><li>Incorrect CVV</li><li>Expired card</li><li>Velocity rules</li><li>Network issues</li></ul><p>Most failures happen <strong>before the money ever moves</strong>.</p><h3>9. Key Configurations That Control Everything</h3><p>These configs influence the full execution flow:</p><ul><li>API keys &amp; environment keys</li><li>Webhook signatures</li><li>Payment intents / Orders API</li><li>Capture rules (manual, auto)</li><li>3D Secure policies</li><li>Allowed card networks</li><li>Retry rules</li><li>Tokenization settings</li><li>SCA / OTP behavior</li><li>Refund rules</li></ul><p>A well-configured gateway = high success rates.</p><h3>10. Final Thoughts</h3><p>Payments look simple on the UI.<br>But under the hood, they are a multilayered conversation involving security, risk engines, global banks, and real-money transfers.</p><p>A developer who understands the internals builds more reliable apps — and solves failures faster.</p><p>This knowledge separates a “checkout developer” from a <strong>payment systems engineer</strong>.</p><p>Want to start preparing for upcoming interviews? I’ve created open repositories with structured questions, patterns, architecture notes, and practical exercises for each stack.</p><p>📌 iOS Interview Prep Repo : <a href="https://github.com/mukundjogi/ios-interview">https://github.com/mukundjogi/ios-interview</a> <br>📌 Android Interview Prep Repo: <a href="https://github.com/mukundjogi/android-interview">https://github.com/mukundjogi/android-interview</a> <br>📌 Flutter Interview Prep Repo: <a href="https://github.com/mukundjogi/flutter-interview">https://github.com/mukundjogi/flutter-interview</a></p><p>If you find them helpful, please ⭐ star the repo — it helps it reach more developers and motivates me to keep adding new content.</p><p>Keep sharing🫰🏻keep learning 🙌🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3093c3ad4b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Push Notifications Work Behind the Scenes]]></title>
            <link>https://medium.com/@mukundjogi/how-push-notifications-work-behind-the-scenes-001dea045956?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/001dea045956</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 04:30:03 GMT</pubDate>
            <atom:updated>2025-12-05T04:30:03.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9C9GdWcO2kPTPOmJUfXN1g.png" /></figure><h4>Mukund Jogi — Mobile App Specialist</h4><h3>1. Introduction</h3><p>Push notifications are the quiet little messengers that keep your apps alive even when you’re not using them. That WhatsApp ping at 2 AM? A missed call alert when your phone was in your pocket? Your banking app reminding you of a bill? All of them rely on a backbone most users never see.</p><p>Modern mobile apps depend heavily on push notifications for engagement, retention, and real-time communication. But the way these notifications travel from an app server to a tiny badge on your screen is far more complex than most people expect.</p><p>Instead of every app building its own push-delivery engine, we rely on specialized notification managers like <strong>Firebase Cloud Messaging (FCM), Apple Push Notification service (APNs), OneSignal, AWS SNS</strong>, and many others. These systems act like global post offices for mobile notifications.</p><p>But reliability isn’t guaranteed. Notifications go missing for dozens of reasons:</p><ul><li>Device offline</li><li>Background restrictions</li><li>OEM customizations</li><li>Token invalidation</li><li>TTL (Time To Live) expired</li><li>App uninstalled</li></ul><p>To understand why this happens, we need to zoom out and look at what actually happens behind the scenes.</p><h3>2. What Actually Happens When an App Sends a Notification</h3><p>Let’s break the flow down in human terms — no jargon, no unnecessary complexity.</p><h3>1. Your server decides to send a message</h3><p>Maybe the user got a new message, maybe there’s a promo, maybe a background job finished. The server triggers a push event.</p><h3>2. A notification payload is created</h3><p>This payload usually contains:</p><ul><li>title</li><li>body</li><li>notification_id</li><li>deep_link (to route user inside the app)</li><li>metadata (sender name, chat ID, campaign ID, etc.)</li><li>priority</li><li>TTL</li></ul><p>It’s just a JSON packet at this stage.</p><h3>3. Your server forwards the payload to a push provider</h3><p>Depending on the platform:</p><ul><li>Android → <strong>FCM</strong></li><li>iOS → <strong>APNs</strong></li><li>Cross-platform → <strong>OneSignal / SNS / custom gateways</strong></li></ul><p>These providers are the “global routers” for mobile notifications.</p><h3>4. Provider converts your payload into an encrypted push packet</h3><p>They sign it with platform-specific keys and wrap it in a secure envelope.</p><h3>5. Packet is routed across the world to the exact device</h3><p>The push provider finds the correct device using the <strong>device token</strong> you previously registered.<br>This step involves internal routing tables, priority queues, and delivery constraints.</p><p>From your server’s perspective, everything is done.<br>But the real magic starts inside the notification provider.</p><h3>3. Deep Dive: The Role of 3rd-Party Notification Managers</h3><p>Services like <strong>FCM, APNs, OneSignal, SNS</strong> do a lot more than send messages. They maintain massive infrastructure to keep billions of devices reachable.</p><p>Here’s what they actually handle.</p><h3>1. Storing device tokens</h3><p>Every device gets a unique token for each app. Providers map:</p><p><strong>AppID → Device → Token → Routing Path</strong></p><p>This ensures notifications reach the correct device and app.</p><h3>2. Knowing whether the app is installed</h3><p>Contrary to myths, providers don’t “check your phone.”<br>Instead:</p><ul><li>When you uninstall an app → its push token becomes invalid</li><li>When they attempt delivery and fail repeatedly → they mark token as dead</li></ul><p>This tells the provider, “The app no longer exists.”</p><h3>3. Maintaining routing tables</h3><p>A global distributed map that decides:</p><ul><li>Which device is online?</li><li>Which data center should deliver?</li><li>Which OEM-specific channel should be used?</li></ul><p>These tables constantly change as devices connect and disconnect.</p><h3>4. TTL, collapse keys &amp; priority</h3><ul><li><strong>TTL</strong>: How long the provider should keep the message if the device is offline</li><li><strong>Collapse key</strong>: Replace older messages with new ones (e.g., location updates)</li><li><strong>Priority</strong>: High priority keeps sockets awake; low priority queues until device wakes</li></ul><h3>5. Queueing notifications for offline devices</h3><p>If the phone is offline, providers store messages temporarily:</p><ul><li>APNs: Keeps messages while the device is unreachable</li><li>FCM: Stores based on TTL</li></ul><h3>6. Delivered / undelivered status</h3><p>Providers track attempts and send status back to your server:</p><ul><li>Delivered</li><li>Failed</li><li>Expired</li><li>Invalid token</li><li>Throttled</li></ul><h3>7. Retry + exponential backoff</h3><p>If delivery fails, they automatically retry using controlled backoff algorithms.</p><p>These services essentially run the world’s largest notification delivery network, so apps don’t have to.</p><h3>4. What Is a Device Token? (Critical Section)</h3><p>A <strong>device token</strong> is your home address in the push-notification world.</p><p>It tells FCM or APNs exactly which device and which app should receive a message.</p><h3>Android: FCM tokens</h3><p>Generated by Google Play Services (or OEM equivalent) when:</p><ul><li>App is installed</li><li>App is opened</li><li>Token is refreshed</li></ul><h3>iOS: APNs tokens</h3><p>Generated when the app requests notification permissions or registers for push.</p><h3>Why tokens change</h3><ul><li>App reinstalled</li><li>Cache cleared</li><li>Device factory reset</li><li>APNs/FCM rotation policies</li><li>User disabled then re-enabled notifications</li></ul><h3>Token = Proof of Installation</h3><p>If a device doesn’t send back a token anymore → the provider assumes the app is gone.</p><h3>How providers know the app was uninstalled</h3><ul><li>FCM/APNs send silent test packets occasionally</li><li>Device fails to acknowledge repeatedly</li><li>Provider marks token invalid → your server gets an error</li></ul><p>This is how they keep routing tables clean.</p><h3>5. Behind-the-Scenes Flow (Detailed Technical Breakdown)</h3><p>Let’s zoom into the lifecycle end to end.</p><h3>1. App opens → gets device token</h3><p>Your app calls:</p><ul><li>FirebaseMessaging.getToken() (Android)</li><li>registerForRemoteNotifications() (iOS)</li></ul><p>The OS generates the token.</p><h3>2. Token sent to your backend</h3><p>Your backend stores:</p><p><strong>user_id → device_id → token → platform</strong></p><h3>3. Backend triggers push</h3><p>A job or event calls your push service.</p><h3>4. Provider validates token</h3><p>“Is this token valid? Is the device reachable?”</p><p>If yes → proceed<br>If no → return error</p><h3>5. Notification routed</h3><p>Depending on device:</p><ul><li><strong>Android</strong> → Google’s messaging backbone</li><li><strong>iOS</strong> → Apple Push Network</li><li><strong>China region</strong> → OEM priority channels (Xiaomi, Huawei, Oppo)</li></ul><h3>6. Device receives packet via a persistent socket</h3><p>Both Android and iOS maintain always-on sockets:</p><ul><li>Lightweight, encrypted</li><li>Battery-optimized</li><li>Reconnected on network change</li></ul><h3>7. Notification shown</h3><p>Depending on app state:</p><ul><li><strong>Foreground</strong> → your app handles it</li><li><strong>Background</strong> → OS displays it</li><li><strong>Killed</strong> → OS handles through system push daemon</li></ul><h3>Delivery factors</h3><p>Real-world issues that impact success:</p><ul><li>Do Not Disturb mode</li><li>Battery optimization (Android aggressive OEMs)</li><li>App force-stopped</li><li>Network switching</li><li>No Google Play services (some regions)</li><li>Competing OEM push services</li></ul><p>This is why two devices may behave very differently.</p><h3>6. ASCII Graphical Flow Diagram</h3><pre>+-------------------+      +--------------------------+        +------------------+<br>|   Your Backend    | ---&gt; | Notification Provider    | -----&gt; |    Device        |<br>|  (App Server)     |      | (FCM / APNs / OneSignal) |        | (Android / iOS)  |<br>+---------+---------+      +------------+-------------+        +---------+--------+<br>          |                              |                              |<br>          | 1. Create payload            |                              |<br>          |-----------------------------&gt;|                              |<br>          |                              | 2. Validate token            |<br>          |                              |-----------------------------&gt;|<br>          |                              |                              | <br>          |                              | 3. Route encrypted packet    |<br>          |                              |-----------------------------&gt;|<br>          |                              |                              |<br>          |                              | &lt;--------- ACK --------------|<br>          |                              |   (delivered/unavailable)    |<br>          | &lt;--------- Status -----------|                              |</pre><h3>7. How Your Device Actually Displays a Notification</h3><p>After delivery, the OS takes over.</p><h3>Android — NotificationManager</h3><ul><li>Uses channels for grouping and importance</li><li>Renders icons, sound, vibration, priority</li><li>Foreground service notifications use higher priority</li><li>Heads-up notifications shown for high importance</li></ul><h3>iOS — UNNotificationCenter</h3><ul><li>Manages categories, actions, styles</li><li>Automatically handles grouping</li><li>Displays according to user’s focus/DND settings</li></ul><h3>Priority</h3><ul><li><strong>High</strong> → delivered immediately, wakes socket</li><li><strong>Normal</strong> → waits for battery-efficient window</li></ul><h3>TTL (Time To Live)</h3><p>If TTL expires before the device becomes reachable → notification is discarded.</p><h3>Collapse keys</h3><p>Prevents spam. Replaces old messages with the latest one.</p><h3>When app code runs</h3><ul><li><strong>Foreground</strong> → your app handles the payload</li><li><strong>Background</strong> → limited processing</li><li><strong>Killed</strong> → zero processing; system displays notification</li></ul><h3>8. How Providers Identify Delivered &amp; Undelivered Status</h3><p>Providers don’t magically know what’s on your screen. They rely on:</p><h3>1. ACK (Acknowledgment) packets</h3><p>Device → provider:<br>“Yes, I received the notification.”</p><h3>2. TTL expiry</h3><p>If the device never comes online → status = expired.</p><h3>3. Invalid tokens</h3><p>App uninstalled → token invalid → undelivered.</p><h3>4. Silent drops</h3><p>Some OEMs (especially Chinese brands) drop low-priority notifications silently.</p><h3>5. Network restrictions</h3><p>VPN, firewalls, roaming networks may block push channels.</p><h3>6. Provider throttling</h3><p>Too many notifications in a short time? They delay or drop some.</p><h3>9. Key Configurations Responsible for Notification Execution</h3><p>Here are the critical settings developers often overlook:</p><ul><li>API keys (server keys)</li><li>Sender IDs</li><li>Device tokens</li><li>TTL</li><li>Priority / importance</li><li>Notification channels (Android)</li><li>Collapse keys</li><li>Topic subscriptions</li><li>Background refresh modes</li><li>App permissions</li><li>APNs certificates / Firebase keys</li><li>Provider dashboard throttling rules</li></ul><p>These configurations define how reliably notifications behave.</p><h3>10. Developer Notes &amp; Best Practices</h3><p>A few practical tips from real-world experience:</p><h3>Handle token rotation gracefully</h3><p>Always update token on app open and on every refresh callback.</p><h3>Use proper importance levels</h3><p>Don’t misuse high-priority unless absolutely needed.</p><h3>Create meaningful notification channels</h3><p>Avoid dumping everything into a single channel.</p><h3>Handle APNs/FCM errors</h3><p>Mark invalid tokens and clean them from DB.</p><h3>Avoid duplicates</h3><p>Check “foreground vs background” logic carefully.</p><h3>Monitor delivery analytics</h3><p>Track:</p><ul><li>sent</li><li>delivered</li><li>failed</li><li>silent drops</li></ul><p>This helps diagnose issues in specific OEM devices.</p><h3>11. Final Thoughts</h3><p>Push notifications look simple from the outside, but under the hood they involve global routing networks, device-level socket connections, OS-level restrictions, and complex reliability engineering.</p><p>If you implement them thoughtfully — with proper token handling, correct priorities, efficient payloads, and monitoring — you’ll get near-WhatsApp-level reliability even at scale.</p><p>As our apps grow, push notifications become more than a feature — they become a backbone of real-time communication. And understanding how they truly work helps us build better, more predictable user experiences.</p><p>Want to start preparing for upcoming interviews? I’ve created open repositories with structured questions, patterns, architecture notes, and practical exercises for each stack.</p><p>📌 <strong>iOS Interview Prep Repo :</strong> <a href="https://github.com/mukundjogi/ios-interview">https://github.com/mukundjogi/ios-interview</a><br>📌 <strong>Android Interview Prep Repo:</strong> <a href="https://github.com/mukundjogi/android-interview">https://github.com/mukundjogi/android-interview</a><br>📌 <strong>Flutter Interview Prep Repo:</strong> <a href="https://github.com/mukundjogi/flutter-interview">https://github.com/mukundjogi/flutter-interview</a></p><p>If you find them helpful, please ⭐ star the repo — it helps it reach more developers and motivates me to keep adding new content.</p><p><strong>Keep sharing🫰🏻keep learning 🙌🏻</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=001dea045956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In-App Purchases on Android: A Deep Dive — Part 2 (with Google Cloud and APIs)]]></title>
            <link>https://medium.com/@mukundjogi/in-app-purchases-on-android-a-deep-dive-part-2-with-google-cloud-and-apis-cd1e551664d0?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1e551664d0</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[in-app-purchase]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 07:12:09 GMT</pubDate>
            <atom:updated>2025-02-14T09:19:22.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>In-App Purchases on Android: A Deep Dive — Part 2 (with Google Cloud and APIs)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5LiYgYdp0qM2mqOppVrLg.png" /></figure><p>In <a href="https://medium.com/@mukundjogi/in-app-purchases-implementation-guide-for-flutter-android-ios-fea806a8ef4b">Part 1</a>, we introduced the concept of In-App Purchases (IAP) and set up our products in the Google Play Console. Part 2 builds on that by diving deeper into the Android-specific implementation and exploring related Google Cloud technologies. We’ll now cover how these technologies work together to create a complete IAP system, focusing on the Google Play Billing Library, the Google Play Developer API, Google Cloud Console, and Cloud Pub/Sub.</p><p><strong>Recap from </strong><a href="https://medium.com/@mukundjogi/in-app-purchases-implementation-guide-for-flutter-android-ios-fea806a8ef4b"><strong>Part 1</strong></a></p><ul><li><strong>IAP Types:</strong> Consumable (used once) and Non-Consumable (permanent unlocks).</li><li><strong>Product Setup:</strong> Products are configured in the Google Play Console with unique IDs.</li><li><strong>Goal:</strong> Implement code that fetches products, handles purchases, verifies them, and manages the app state accordingly.</li></ul><p><strong>II. Diving Deeper: Key Concepts, Technologies, Google Cloud and Testing</strong></p><p>Let’s explore the core aspects of Android IAP, including the mentioned Google Cloud technologies, referencing the <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fdeveloper.android.com%2Fgoogle%2Fplay%2Fbilling"><strong>Google Play Billing Documentation</strong></a>.</p><p><strong>A. The Core: Google Play Billing Library</strong></p><p>As discussed before, the <strong>Google Play Billing Library</strong> is an API that helps you to communicate with the Play Store for all purchase-related activities. This API is a part of your Android app and helps you to fetch product details, handle purchases, and more.</p><ul><li>BillingClient: Manages communication with Google Play.</li><li>Purchase: Represents a purchase by a user.</li><li>ProductDetails: Contains information about a specific product.</li><li>BillingFlowParams: Used to launch purchase flows.</li></ul><p><strong>B. Google Cloud Console and the Google Play Developer API</strong></p><p>The <a href="https://console.cloud.google.com/"><strong>Google Cloud Console</strong></a> is a powerful platform for managing your Google Cloud resources, including backend APIs like the <strong>Google Play Developer API</strong>.</p><ul><li><strong>Backend verification:</strong> You can use the API to securely verify purchases on your server and check the status of subscriptions.</li><li><strong>Automated product management:</strong> You can automate the creation, updates, and deletion of in-app products from the backend.</li><li><strong>Access purchase history:</strong> Retrieve purchase history programmatically.</li></ul><p><strong>C. Connecting to the Billing Library (App Side)</strong></p><ul><li><strong>Build BillingClient:</strong> Initialize BillingClient using the builder and enable enablePendingPurchases.</li></ul><pre>private lateinit var billingClient: BillingClient<br>private fun setupBillingClient() {<br>    billingClient = BillingClient.newBuilder(this)<br>        .setListener(purchasesUpdatedListener)<br>        .enablePendingPurchases()<br>        .build()<br>}</pre><ul><li><strong>Connect to Billing Service:</strong> Call the startConnection with BillingClientStateListener.</li></ul><pre>billingClient.startConnection(object : BillingClientStateListener {<br>        override fun onBillingSetupFinished(billingResult: BillingResult) {<br>            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>                // Connection Successful<br>                queryProducts()<br>            } else {<br>                Log.e(&quot;Billing&quot;, &quot;Billing setup failed with code: ${billingResult.responseCode}&quot;)<br>            }<br>        }<br><br>        override fun onBillingServiceDisconnected() {<br>            // Try to restart the connection.<br>            Log.e(&quot;Billing&quot;, &quot;Billing Service Disconnected.&quot;)<br>           setupBillingClient()<br>        }<br>    })</pre><p><strong>D. Querying Product Details (App Side)</strong></p><ul><li><strong>Prepare QueryProductDetailsParams:</strong> Fetch details using QueryProductDetailsParams with Product IDs.</li></ul><pre>private fun queryProducts() {<br>    val queryProductDetailsParams = QueryProductDetailsParams.newBuilder()<br>        .setProductList(<br>            ImmutableList.of(<br>                QueryProductDetailsParams.Product.newBuilder()<br>                    .setProductId(&quot;premium_access&quot;) // Your Product ID<br>                    .setProductType(BillingClient.ProductType.INAPP)<br>                    .build()<br>            )<br>        )<br>        .build()<br><br>    billingClient.queryProductDetailsAsync(queryProductDetailsParams) { billingResult, productDetailsList -&gt;<br>        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>            // Handle product details.<br>           for (productDetails in productDetailsList) {<br>                //Display product in UI<br>           }<br>        } else {<br>             Log.e(&quot;Billing&quot;, &quot;Product details query failed: ${billingResult.debugMessage}&quot;)<br>        }<br>    }<br>}</pre><p><strong>E. Handling Purchases (App Side)</strong></p><ul><li><strong>Set Purchase Listener:</strong> Implement PurchasesUpdatedListener for handling purchases</li></ul><pre>private val purchasesUpdatedListener = PurchasesUpdatedListener { billingResult, purchases -&gt;<br>    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK &amp;&amp; purchases != null) {<br>        for (purchase in purchases) {<br>          // Handle purchase<br>            handlePurchase(purchase)<br>        }<br>    } else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {<br>        // Handle cancelation<br>       Log.e(&quot;Billing&quot;, &quot;Purchase canceled by user.&quot;)<br>    } else {<br>        // Handle Purchase error<br>        Log.e(&quot;Billing&quot;, &quot;Purchase error with code: ${billingResult.responseCode}&quot;)<br>    }<br>}</pre><p><strong>F. Purchase State Management and Acknowledgement (App Side)</strong></p><ul><li><strong>Handle Purchase:</strong> Manage purchases with different states (PURCHASED or PENDING).</li></ul><pre>private fun handlePurchase(purchase: Purchase) {<br>    if (purchase.purchaseState == PurchaseState.PURCHASED) {<br>        // Handle purchase logic<br>        if (!purchase.isAcknowledged) {<br>            acknowledgePurchase(purchase)<br>        }<br>    } else if (purchase.purchaseState == PurchaseState.PENDING) {<br>       // Handle pending state.<br>    }<br>}</pre><ul><li><strong>Acknowledge Purchases:</strong> Use billingClient.acknowledgePurchase() to acknowledge purchases after product delivery.</li></ul><pre>private fun acknowledgePurchase(purchase: Purchase) {<br>   val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()<br>        .setPurchaseToken(purchase.purchaseToken)<br>        .build()<br><br>   billingClient.acknowledgePurchase(acknowledgePurchaseParams) { billingResult -&gt;<br>        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>            // Purchase acknowledged<br>        } else {<br>             //Handle acknowledgment error<br>              Log.e(&quot;Billing&quot;, &quot;Purchase acknowledgement failed: ${billingResult.debugMessage}&quot;)<br>        }<br>    }<br>}</pre><p><strong>G. Consuming Products (App Side)</strong></p><ul><li><strong>Consume Products:</strong> Call billingClient.consumeAsync() for consumable products to allow repurchase.</li></ul><pre>private fun consumePurchase(purchase: Purchase) {<br>    val consumeParams = ConsumeParams.newBuilder()<br>        .setPurchaseToken(purchase.purchaseToken)<br>        .build()<br><br>   billingClient.consumeAsync(consumeParams) { billingResult, purchaseToken -&gt;<br>        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>            // Product consumed successfully.<br>        } else {<br>            // Handle Consumption error<br>             Log.e(&quot;Billing&quot;, &quot;Purchase consumption failed: ${billingResult.debugMessage}&quot;)<br>        }<br>    }<br>}</pre><p><strong>H. Initiating the Purchase Flow (App Side)</strong></p><ul><li><strong>Launch Purchase:</strong> Use billingClient.launchBillingFlow() to launch the purchase flow using ProductDetails.</li></ul><pre>fun startPurchaseFlow(product: ProductDetails) {<br>      val productDetailsParamsList =<br>          listOf(<br>              BillingFlowParams.ProductDetailsParams.newBuilder()<br>                  .setProductDetails(product)<br>                  .build()<br>          )<br>      val billingFlowParams = BillingFlowParams.newBuilder()<br>          .setProductDetailsParamsList(productDetailsParamsList)<br>          .build()<br><br>      val billingResult = billingClient.launchBillingFlow(this, billingFlowParams)<br>      if(billingResult.responseCode != BillingClient.BillingResponseCode.OK) {<br>            // Handle launch billing flow error.<br>            Log.e(&quot;Billing&quot;, &quot;Launch billing flow failed with code: ${billingResult.responseCode}&quot;)<br>      }<br>  }</pre><p><strong>I. Cloud Pub/Sub and Real-Time Developer Notifications (RTDN) (Server Side)</strong></p><p><a href="https://cloud.google.com/pubsub"><strong>Cloud Pub/Sub</strong></a> is a fully managed real-time messaging service from Google Cloud. Google Play uses Cloud Pub/Sub to deliver <strong>real-time developer notifications (RTDN)</strong> for subscription events. These notifications can be configured in the Google Play Console.</p><p><strong>Use Cases:</strong></p><ul><li><strong>Subscription Status Updates:</strong> Receive immediate notifications for subscription events like renewals, cancellations, and expirations.</li><li><strong>Real-Time Data:</strong> Get up-to-date purchase data pushed directly to your server.</li><li><strong>Automation:</strong> Automate backend processes such as granting access to features or content.</li></ul><p><strong>How it Works:</strong></p><ol><li><strong>Set Up Pub/Sub:</strong> In your Google Cloud Console project, create a Pub/Sub topic and subscription.</li><li><strong>Configure in Google Play Console:</strong> Link your Pub/Sub topic to your Google Play app in the console.</li><li><strong>Receive Notifications:</strong> Your server receives real-time messages whenever there is a subscription event.</li></ol><p><strong>J. Testing Your In-App Purchases (Crucial!)</strong></p><p>Before launching your app with IAP, thorough testing is essential to ensure a seamless user experience. This includes setting up internal testers and external testers.</p><ol><li><strong>Create a Test Group:</strong></li></ol><ul><li>In the Google Play Console, navigate to “Release” &gt; “Testing” (e.g., Internal testing, Closed testing, Open testing).</li><li>Choose a testing track based on how widely you want to release your app (internal is for your immediate team, closed is for a limited group, and open is for anyone who wants to join).</li><li>Create an email list (Google Group) to manage your testers or upload a CSV file of email addresses.</li></ul><p><strong>2. Add Testers to the Test Group:</strong></p><ul><li>Enter the email addresses of the testers or link the existing Google group to your application.</li></ul><p><strong>3. Use Test Accounts:</strong></p><ul><li>Make sure your testers have Google accounts and those accounts are added to the testing group.</li><li>Testers will need to install the test version of your app from the Play Store (using the opt-in link provided in the test track setup).</li></ul><p><strong>4. Testing Different Scenarios:</strong></p><ul><li>Test successful purchases.</li><li>Test purchase cancellations (user-initiated).</li><li>Test deferred purchases (e.g., “Ask to buy” in Family Sharing).</li><li>Test error handling.</li><li>Test subscription renewals, expirations, and cancellations (if you’re using subscriptions).</li><li>Test restore Purchases</li></ul><p><strong>5. Enable License Testing (for older versions of the Billing Library):</strong></p><ul><li><strong>Navigate to License Testing:</strong> Go to the “<a href="https://play.google.com/console/u/0/developers"><strong>Home Page Google Play Console</strong></a>” → “<strong>Settings</strong>” → “<strong>License Testing”</strong> section in the Google Play Console.</li><li><strong>Add Test Accounts:</strong> Add the Google accounts you want to use for testing in-app purchases</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Quc_tpb1c_AbWofI.png" /></figure><ul><li><strong>Important:</strong> For the testing of the subscriptions, remember that test subscriptions renew frequently (e.g., daily, weekly) to facilitate testing.</li><li>Remember, your test users should not use their primary Google account if they are purchasing in-app purchases with testing credentials, and it should only be used with a dedicated testing account.</li></ul><p><strong>III. Key Takeaways</strong></p><ul><li><strong>Billing Library:</strong> The core API for handling purchases in your Android app.</li><li><strong>Google Cloud Console:</strong> A platform to manage your Google Cloud resources.</li><li><strong>Google Play Developer API:</strong> Enables you to programmatically manage your Google Play app and products.</li><li><strong>Cloud Pub/Sub:</strong> Delivers real-time subscription notifications to your backend, which are configured in the Google Play console.</li></ul><p><strong>IV. Useful Links</strong></p><ul><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fdeveloper.android.com%2Fgoogle%2Fplay%2Fbilling"><strong>Google Play Billing Library documentation</strong></a></li><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fdevelopers.google.com%2Fandroid-publisher%2Fapi-ref"><strong>Google Play Developer API</strong></a></li><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Fpubsub"><strong>Cloud Pub/Sub</strong></a></li><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fdeveloper.android.com%2Fgoogle%2Fplay%2Fbilling%2Frtdn"><strong>Real-time developer notifications (RTDN)</strong></a></li><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fsupport.google.com%2Fgoogleplay%2Fandroid-developer%2Fanswer%2F3060016%3Fhl%3Den"><strong>Set up license testing — Google Play Help</strong></a></li><li><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fsupport.google.com%2Fgoogleplay%2Fandroid-developer%2Fanswer%2F3060016%3Fhl%3Den"><strong>Set up open, closed, or internal test</strong></a><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fsupport.google.com%2Fgoogleplay%2Fandroid-developer%2Fanswer%2F3131213%3Fhl%3Den"><strong>ing</strong></a> <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fsupport.google.com%2Fgoogleplay%2Fandroid-developer%2Fanswer%2F3060016%3Fhl%3Den"><strong>— Play Console Help</strong></a></li><li><a href="https://support.google.com/googleplay/android-developer/answer/6062777"><strong>Test in-app billing with application licensing</strong></a></li></ul><p>Part 2, expanded with Google Cloud technologies and testing, provides a comprehensive picture of Android IAP. Thorough testing with test accounts ensures a smooth IAP experience for your users. Remember to consult the official documentation. <strong>Now that you have a strong understanding of Android IAP, Part 3 will guide you through the process of implementing In-App Purchases on iOS, providing insights into App Store Connect configuration and the StoreKit framework.</strong></p><p><em>Originally published at </em><a href="https://mukundjogi.hashnode.dev/in-app-purchases-on-android-a-deep-divepart-2-with-google-cloud-and-apis"><em>https://mukundjogi.hashnode.dev</em></a><em> on February 14, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1e551664d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In-App Purchases: Implementation Guide for Flutter, Android & iOS]]></title>
            <link>https://medium.com/@mukundjogi/in-app-purchases-implementation-guide-for-flutter-android-ios-fea806a8ef4b?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea806a8ef4b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[in-app-purchase]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 13:43:11 GMT</pubDate>
            <atom:updated>2025-02-14T07:39:46.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiXU2vDmvP0lbX0lRm3ScA.png" /></figure><p>Welcome to the first part of our series on implementing In-App Purchases (IAP). In this post, we’ll cover the fundamental concepts of IAP, explore why they are crucial for app monetization, and provide an overview of essential documentation. We’ll also guide you through the initial steps of setting up your applications in both the Google Play Console and App Store Connect.</p><p><strong>What are In-App Purchases (IAP)?</strong></p><p>In-App Purchases (IAP) are the purchase of digital goods or services directly within a mobile app. They offer a flexible way for developers to monetize their apps, providing a variety of content and features to users.</p><p><strong>Types of In-App Purchases</strong></p><p>There are primarily three types of IAP:</p><ol><li><strong>Consumable Items:</strong> Items that can be purchased multiple times and are “used up” (e.g., in-game currency, lives).</li><li><strong>Non-Consumable Items:</strong> Items purchased once and remain available to the user indefinitely (e.g., premium features, ad removal).</li><li><strong>Subscriptions:</strong> Provide access to content or services for a recurring fee (e.g., premium content access, monthly memberships).</li></ol><p><strong>Why Use In-App Purchases?</strong></p><p>Implementing IAP offers significant benefits:</p><ul><li><strong>Revenue Generation:</strong> IAP provides a direct method to monetize your app beyond its initial purchase price.</li><li><strong>Flexibility and Choice:</strong> You can provide a wide range of digital goods and features, catering to different user needs and interests.</li><li><strong>Improved User Engagement:</strong> IAP can lead to increased user engagement by offering premium features or content.</li><li><strong>Scalability and Long-term Revenue:</strong> IAP enables you to adjust and expand your product offerings to scale your app and provide long-term revenue.</li></ul><p><strong>Overview of Useful Links</strong></p><p>This series will utilize the official documentation from Google and Apple. Here’s a brief overview of the resources we’ll be referencing:</p><p><strong>Android:</strong></p><p><a href="https://developer.android.com/google/play/billing"><strong>Google Play Billing</strong></a><strong>:</strong></p><ul><li>The core documentation for Android In-App Purchases. Provides in-depth information on the Play Billing Library, how to implement the purchase flow, and various testing strategies.</li></ul><p><a href="https://developers.google.com/android-publisher/api-ref"><strong>Google Play Developer API</strong></a><strong>:</strong></p><ul><li>A REST API that enables you to manage your app listings programmatically, including handling reviews, ratings, and in-app products.</li></ul><p><a href="https://developer.android.com/google/play/billing/getting-ready#configure-rtdn"><strong>Real-time developer notifications (RTDN)</strong></a><strong>:</strong></p><ul><li>Google Play Console publishes real-time updates about the subscriptions.</li></ul><p><strong>iOS:</strong></p><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/overview-for-configuring-in-app-purchases"><strong>App Store Connect IAP Overview</strong></a><strong>:</strong></p><ul><li>An overview of how to configure in-app purchases in App Store Connect. Covers the different IAP types, settings, and best practices.</li></ul><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/generate-keys-for-in-app-purchases"><strong>Generate Keys for IAP</strong></a></p><ul><li>Guidance on how to generate API keys for server-side interactions with the App Store API.</li></ul><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/generate-a-shared-secret-to-verify-receipts"><strong>Generate Shared Secret</strong></a><strong>:</strong></p><ul><li>Instructions on how to generate a shared secret to verify purchase receipts securely.</li></ul><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/enter-server-urls-for-app-store-server-notifications"><strong>Server URLs for Notifications:</strong></a></p><ul><li>Details on setting up your server URLs to receive real-time notifications for various IAP events, including subscription changes.</li></ul><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/set-a-tax-category-for-in-app-purchases"><strong>Set a Tax Category for In-App Purchases</strong></a>:</p><ul><li>Set tax categories for your in-app purchases.</li></ul><p><a href="https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/turn-on-family-sharing-for-in-app-purchases"><strong>Turn On Family Sharing for In-App Purchases</strong></a><strong>:</strong></p><ul><li>Information on how to enable family sharing for your IAP products.</li></ul><p><a href="https://developer.apple.com/documentation/storekit/in-app_purchase"><strong>StoreKit Documentation</strong></a><strong>:</strong></p><ul><li>Provides detailed guides and API information on how to implement IAP in iOS apps.</li></ul><p><strong>Initial App Setup in Google Play Console and App Store Connect</strong></p><p>This step is crucial and involves some common practices.</p><ol><li><strong>Create a Developer Account:</strong> You need to have a developer account for both the Google Play Console and App Store Connect.</li><li><strong>Set up your App:</strong> Create an app entry in each store, filling out necessary information like app name, description, and screenshots. Make sure that you are using a correct Bundle Identifier.</li><li><strong>Create In-App Products:</strong></li></ol><ul><li><strong>Android (Google Play Console):</strong> Navigate to “Monetize with Play” &gt; “Products” &gt; “In-app products.” Here you create the product that can be purchased in your app</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UIBrLqjoMOnzATw" /></figure><p><strong>iOS (App Store Connect):</strong> Go to “Monetization” &gt; “In-App Purchases”. Here you create the product that can be purchased in your app.</p><ul><li>For each product, set up details like a unique product ID, a descriptive title, a price, and a description. Make sure to choose consumable or non-consumable according to your business logic.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j6czg6ePrpYRqfPg" /></figure><p><strong>Key Takeaways</strong></p><ul><li>In-App Purchases are powerful tools for app monetization.</li><li>You have three main types of IAP to consider for your apps (consumable, non-consumable, subscription).</li><li>You need to setup the application in both the consoles, prior to any implementation.</li><li>Official documentation provides a deeper understanding of the IAP process.</li></ul><p><strong>Next Steps</strong></p><p>In <a href="https://mukundjogi.hashnode.dev/in-app-purchases-on-android-a-deep-divepart-2-with-google-cloud-and-apis?source=more_series_bottom_blogs">Part 2</a>, we will focus on integrating IAP in Android using Kotlin and the Google Play Billing Library. We will use the above links for further information.</p><p><em>Originally published at </em><a href="https://mukundjogi.hashnode.dev/part-1-introduction-and-setup"><em>https://mukundjogi.hashnode.dev</em></a><em> on February 11, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea806a8ef4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative UI: APIs, MVVM, State (SwiftUI, Compose, Flutter)]]></title>
            <link>https://medium.com/@mukundjogi/declarative-ui-apis-mvvm-state-swiftui-compose-flutter-89ab9b650012?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ab9b650012</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[declarative-ui]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 08:55:06 GMT</pubDate>
            <atom:updated>2025-01-20T09:03:33.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6dYMeQBeDGcnND0" /></figure><p>Hey everyone! 👋 We’ve been on quite a journey, exploring declarative UI, state management, and sealed classes. Today, I am bringing it all together with the MVVM architectural pattern. We’ll see how MVVM, along with proper state management using sealed classes/enums, can supercharge our apps when handling API calls. And of course, we’ll explore this in SwiftUI, Jetpack Compose, and Flutter, while emphasizing the necessity of segregation.</p><p><strong>Why Segregation Matters?</strong></p><p>Before diving into the code, let’s talk about <em>why</em> we need to segregate our code. Imagine trying to bake a cake with all the ingredients mixed together — it’s a recipe for disaster! Similarly, in app development, if we don’t separate our code based on responsibilities, we end up with a tangled mess that’s hard to understand, debug, and maintain.</p><p><strong>MVVM, Sealed Classes/Enums, and APIs</strong></p><p>In this setup:</p><ul><li>The <strong>model</strong> handles data-related operations (API calls, database interactions).</li><li>The <strong>ViewModel</strong> fetches data using the Model, manages UI state, and exposes this state to the View. We’ll use sealed classes/enums to represent these UI states.</li><li>The <strong>View</strong> observes the ViewModel’s state and updates the UI declaratively.</li></ul><p>Let’s see it in action.</p><p><strong>SwiftUI: MVVM with Combine and Enums</strong></p><pre>import SwiftUI<br>import Combine<br><br>// MARK: - Model (API Handling)<br>struct Photo: Codable, Identifiable {<br>    let id: Int<br>    let title: String<br>    let thumbnailUrl: String<br>}<br><br>class ApiClient {<br>    func fetchPhotos() -&gt; AnyPublisher&lt;[Photo], Error&gt; {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/photos&quot;) else {<br>            return Fail(error: URLError(.badURL)).eraseToAnyPublisher()<br>        }<br>        return URLSession.shared.dataTaskPublisher(for: url)<br>            .map {$0.data }<br>            .decode(type: [Photo].self, decoder: JSONDecoder())<br>            .eraseToAnyPublisher()<br>    }<br>}<br><br>// MARK: - ViewModel<br>enum ViewState&lt;T&gt; {<br>    case loading<br>    case loaded(data: T)<br>    case error(message: String)<br>}<br><br>class PhotoViewModel: ObservableObject {<br>    @Published var viewState: ViewState&lt;[Photo]&gt; = .loading<br>    private let apiClient = ApiClient()<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    func fetchPhotos() {<br>        viewState = .loading<br>        apiClient.fetchPhotos()<br>           .sink(receiveCompletion: { completion in<br>                switch completion {<br>                    case .finished: break<br>                    case .failure(let error):<br>                        self.viewState = .error(message: error.localizedDescription)<br>                }<br>            }, receiveValue: { photos in<br>              self.viewState = .loaded(data: photos)<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>// MARK: - View<br>struct PhotoListView: View {<br>    @StateObject var viewModel = PhotoViewModel()<br><br>    var body: some View {<br>        VStack {<br>            switch viewModel.viewState {<br>                case .loading:<br>                     ProgressView(&quot;Loading...&quot;)<br>                case .loaded(let photos):<br>                    List(photos) { photo in<br>                      Text(photo.title)<br>                    }<br>                case .error(let message):<br>                     Text(&quot;Error: \(message)&quot;).foregroundColor(.red)<br>            }<br>        }.onAppear {<br>            viewModel.fetchPhotos()<br>        }<br>    }<br>}</pre><ul><li><strong>Model</strong>: ApiClient fetches data using URLSession and returns a Combine Publisher.</li><li><strong>ViewModel</strong>: PhotoViewModel transforms the Model’s data into a ViewState and exposes it using <a href="https://hashnode.com/@Published">@Published</a> for UI to observe.</li><li><strong>View</strong>: PhotoListView observes viewModel.viewState and renders UI declaratively based on that state.</li></ul><p><strong>Jetpack Compose: MVVM with Sealed Classes</strong></p><pre>import androidx.compose.foundation.layout.*<br>import androidx.compose.material.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.viewModelScope<br>import kotlinx.coroutines.launch<br>import kotlinx.serialization.SerialName<br>import kotlinx.serialization.Serializable<br>import kotlinx.serialization.json.Json<br>import java.net.URL<br><br>// MARK: - Model<br>@Serializable<br>data class Album(<br>    @SerialName(&quot;id&quot;) val id: Int,<br>    @SerialName(&quot;title&quot;) val title: String<br>)<br><br>class ApiService {<br>   suspend fun fetchAlbums(): List&lt;Album&gt; {<br>     val url = URL(&quot;https://jsonplaceholder.typicode.com/albums&quot;)<br>     val jsonString = url.readText()<br>     return Json.decodeFromString(jsonString)<br>   }<br>}<br><br>// MARK: - View Model<br>sealed class ViewState&lt;out T&gt; {<br>    object Loading : ViewState&lt;Nothing&gt;()<br>    data class Loaded&lt;T&gt;(val data: T) : ViewState&lt;T&gt;()<br>    data class Error(val message: String) : ViewState&lt;Nothing&gt;()<br>}<br><br>class AlbumViewModel: ViewModel() {<br>    private val apiService = ApiService()<br>    var viewState by mutableStateOf&lt;ViewState&lt;List&lt;Album&gt;&gt;&gt;(ViewState.Loading)<br>        private set<br><br>    init {<br>        fetchAlbums()<br>    }<br><br>    private fun fetchAlbums() {<br>         viewModelScope.launch {<br>            try {<br>                val albums = apiService.fetchAlbums()<br>                viewState = ViewState.Loaded(albums)<br>            }catch (e: Exception) {<br>               viewState = ViewState.Error(e.localizedMessage ?: &quot;An error occurred&quot;)<br>            }<br>         }<br>    }<br>}<br><br>// MARK: - View<br>@Composable<br>fun AlbumListScreen(viewModel: AlbumViewModel = AlbumViewModel()) {<br>    val viewState = viewModel.viewState<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>       when(viewState) {<br>           is ViewState.Loading -&gt; {<br>               CircularProgressIndicator()<br>                Text(text=&quot;Loading...&quot;)<br>           }<br>           is ViewState.Loaded -&gt; {<br>               val albums = (viewState as ViewState.Loaded&lt;List&lt;Album&gt;&gt;).data<br>                 if (albums.isNotEmpty()) {<br>                     Column {<br>                         albums.forEach { album -&gt;<br>                             Text(text = album.title, style = MaterialTheme.typography.h6)<br>                         }<br>                     }<br>                 }else{<br>                    Text(text=&quot;No data to display&quot;)<br>                 }<br>           }<br>           is ViewState.Error -&gt; {<br>              val errorMessage = (viewState as ViewState.Error).message<br>             Text(text=&quot;Error: $errorMessage&quot;, color = MaterialTheme.colors.error)<br>           }<br>       }<br>    }<br>}</pre><ul><li><strong>Model</strong>: ApiService fetches data using a URL.</li><li><strong>ViewModel</strong>: AlbumViewModel fetches albums and holds a ViewState, which can be loading, success, or error.</li><li><strong>View</strong>: AlbumListScreen uses the viewState to render the UI accordingly.</li></ul><p><strong>Flutter: MVVM with BLoC and Enums</strong></p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>// MARK: - Model<br>class Todo {<br>  final int id;<br>  final String title;<br><br>  Todo({required this.id, required this.title});<br>  factory Todo.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return Todo(id: json[&#39;id&#39;], title: json[&#39;title&#39;]);<br>  }<br>}<br><br>class ApiService {<br>  Future&lt;List&lt;Todo&gt;&gt; fetchTodos() async {<br>    final response =<br>        await http.get(Uri.parse(&#39;https://jsonplaceholder.typicode.com/todos&#39;));<br>    if (response.statusCode == 200) {<br>      final List&lt;dynamic&gt; jsonList = jsonDecode(response.body);<br>      return jsonList.map((json) =&gt; Todo.fromJson(json)).toList();<br>    } else {<br>      throw Exception(&#39;Failed to load todos&#39;);<br>    }<br>  }<br>}<br><br>// MARK: - BLoC Events<br>sealed class TodoEvent {}<br>class FetchTodos extends TodoEvent {}<br><br>// MARK: - BLoC State<br>enum ViewState { loading, loaded, error }<br><br>class TodoState {<br>  final ViewState state;<br>  final List&lt;Todo&gt;? todos;<br>  final String? errorMessage;<br><br>  TodoState({required this.state, this.todos, this.errorMessage});<br>}<br><br>// MARK: - BLoC<br>class TodoBloc extends Bloc&lt;TodoEvent, TodoState&gt; {<br>  final ApiService apiService;<br><br>  TodoBloc({required this.apiService}) : super(TodoState(state: ViewState.loading)) {<br>    on&lt;FetchTodos&gt;((event, emit) async {<br>        emit(TodoState(state: ViewState.loading));<br>      try {<br>        final todos = await apiService.fetchTodos();<br>        emit(TodoState(state: ViewState.loaded, todos: todos));<br>      } catch (e) {<br>        emit(TodoState(state: ViewState.error, errorMessage: e.toString()));<br>      }<br>    });<br>      add(FetchTodos());<br>  }<br>}<br><br><br>// MARK: - View<br>class TodoListScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; TodoBloc(apiService: ApiService()),<br>      child: Scaffold(<br>        appBar: AppBar(title: Text(&#39;Todo List&#39;)),<br>        body: Center(<br>          child: BlocBuilder&lt;TodoBloc, TodoState&gt;(<br>            builder: (context, state) {<br>              switch (state.state) {<br>                case ViewState.loading:<br>                  return CircularProgressIndicator();<br>                case ViewState.loaded:<br>                  final todos = state.todos;<br>                  return ListView.builder(<br>                    itemCount: todos!.length,<br>                    itemBuilder: (context, index) {<br>                      return ListTile(title: Text(todos[index].title));<br>                    },<br>                  );<br>                case ViewState.error:<br>                  return Text(&quot;Error: ${state.errorMessage}&quot;);<br>              }<br>            },<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Model:</strong> ApiService fetches todo data, while Todo represents a single todo item.</li><li><strong>BLoC:</strong> TodoBloc receives events, uses ApiService to fetch todos, and emits states (loading, loaded, or error).</li><li><strong>View:</strong> TodoListScreen listens to TodoBloc’s state and updates its UI accordingly using BlocBuilder.</li></ul><p><strong>Benefits of MVVM and Segregation</strong></p><ul><li><strong>Clear Code Structure</strong>: Code becomes much more organized and easier to read due to clear separation of concerns.</li><li><strong>Easy Testing:</strong> You can test the ViewModel and Model in isolation, improving the reliability of your code.</li><li><strong>Maintainability:</strong> Code becomes modular and easier to modify or extend as the application grows.</li><li><strong>Scalability:</strong> The architecture is well-suited to scale as the app becomes more complex.</li><li><strong>Reusability:</strong> ViewModels and Models can be reused across different views.</li></ul><p><strong>Wrapping Up</strong></p><p>Using MVVM with state management, sealed classes/enums, and declarative UI not only simplifies the process of building modern applications but also gives us a more robust and scalable architecture. By adhering to these principles and separating concerns effectively, we can write cleaner, more maintainable, and ultimately, better applications.</p><p>Let me know if you see any areas where I can make this explanation even better! I’m always up for suggestions and improvements.</p><p>Clap-clap-clap… clap-clap-clap… Keep clapping until you hit 10! 🎉</p><p>Ready to level up your Declarative UI skills? Explore my recent <a href="https://mukundjogi.hashnode.dev/series/magic-of-declarative-ui">series</a>.</p><p>Let’s keep sharing, learning, and practicing! 🤘🏻</p><p><em>Originally published at </em><a href="https://mukundjogi.hashnode.dev/the-power-of-mvvm-state-management-apis-and-declarative-ui-in-swiftui-compose-and-flutter"><em>https://mukundjogi.hashnode.dev</em></a><em> on January 20, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ab9b650012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret to Easy API Calls: Interceptors in Declarative UI]]></title>
            <link>https://medium.com/@mukundjogi/the-secret-to-easy-api-calls-interceptors-in-declarative-ui-d40c33fdd8e6?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40c33fdd8e6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 07:00:31 GMT</pubDate>
            <atom:updated>2024-11-11T07:07:13.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d5I17-GUo6_wdBPr" /></figure><p>Imagine building an app that needs to fetch data from a server. You’d write code to make API calls, parse the data, and handle any errors. This can be a lot of repetitive code, especially if you’re using the same API calls in different parts of your app.</p><p>Enter network call interceptors! They’re like little helpers that sit between your app and the server, handling the tedious tasks of making API calls and processing data. This makes your code cleaner, more reusable, and easier to maintain.</p><p>Let’s see how this works in SwiftUI, Compose, and Flutter:</p><p><strong>1. SwiftUI</strong></p><p>In SwiftUI, we can use URLSession to make API calls. We can create an interceptor that handles the request and response:</p><pre>// Interceptor class<br>class APIInterceptor {<br>  static func intercept(url: URL, completion: @escaping (Data?, Error?) -&gt; Void) {<br>    URLSession.shared.dataTask(with: url) { data, response, error in<br>      if let error = error {<br>        completion(nil, error)<br>        return<br>      }<br><br>      if let data = data {<br>        completion(data, nil) <br>      }<br>    }.resume()<br>  }<br>}</pre><p>Now, you can easily use this interceptor in your SwiftUI views:</p><pre>struct MyView: View {<br>  @State private var data: [String] = []<br><br>  var body: some View {<br>    List(data, id: \.self) { item in<br>      Text(item)<br>    }<br>    .onAppear {<br>      APIInterceptor.intercept(url: URL(string: &quot;https://api.example.com/data&quot;)!) { data, error in<br>        if let error = error {<br>          print(&quot;Error fetching data: \(error)&quot;)<br>        } else if let data = data {<br>          // Parse the data to an array of strings<br>          let decoder = JSONDecoder()<br>          if let decodedData = try? decoder.decode([String].self, from: data) {<br>            self.data = decodedData<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>2. Compose</strong></p><p>Compose uses Kotlin coroutines for asynchronous operations. Here’s how you can create an interceptor in Compose:</p><pre>object APIInterceptor {<br>  suspend fun &lt;T&gt; intercept(url: String, parser: (String) -&gt; T): T {<br>    try {<br>      val response = HttpClient.get(url)<br>      val data = response.body&lt;String&gt;()<br>      return parser(data) // Parse the data to the desired type<br>    } catch (e: Exception) {<br>      throw e<br>    }<br>  }<br>}</pre><p>You can then call the interceptor from a Compose Composable function:</p><pre>@Composable<br>fun MyScreen() {<br>  val data = remember { mutableStateListOf&lt;String&gt;() } <br><br>  LaunchedEffect(Unit) {<br>    try {<br>      val fetchedData = APIInterceptor.intercept(&quot;https://api.example.com/data&quot;) {<br>        // Parse the JSON string to an array of strings<br>        Gson().fromJson(it, Array&lt;String&gt;::class.java).toList()<br>      }<br>      data.addAll(fetchedData)<br>    } catch (e: Exception) {<br>      Log.e(&quot;MyScreen&quot;, &quot;Error fetching data: ${e.message}&quot;)<br>    }<br>  }<br><br>  // Display the data using Compose components<br>  Column {<br>    data.forEach { item -&gt;<br>      Text(item)<br>    }<br>  }<br>}</pre><p><strong>3. Flutter</strong></p><p>Flutter uses the http package for API calls. Here’s an interceptor example:</p><pre>class APIInterceptor {<br>  static Future&lt;dynamic&gt; intercept(String url) async {<br>    try {<br>      final response = await http.get(Uri.parse(url));<br>      if (response.statusCode == 200) {<br>        // Parse the response body to the desired type<br>        return jsonDecode(response.body); <br>      } else {<br>        throw Exception(&quot;API request failed with status code ${response.statusCode}&quot;);<br>      }<br>    } catch (e) {<br>      throw e;<br>    }<br>  }<br>}</pre><p>Then, in your Flutter widget:</p><pre>class MyWidget extends StatefulWidget {<br>  @override<br>  _MyWidgetState createState() =&gt; _MyWidgetState();<br>}<br><br>class _MyWidgetState extends State&lt;MyWidget&gt; {<br>  List&lt;String&gt; data = [];<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    fetchData();<br>  }<br><br>  Future&lt;void&gt; fetchData() async {<br>    try {<br>      final fetchedData = await APIInterceptor.intercept(&quot;https://api.example.com/data&quot;);<br>      setState(() {<br>        data = fetchedData.cast&lt;String&gt;().toList();<br>      });<br>    } catch (e) {<br>      print(&quot;Error fetching data: ${e.toString()}&quot;);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.builder(<br>      itemCount: data.length,<br>      itemBuilder: (context, index) {<br>        return ListTile(<br>          title: Text(data[index]),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p><strong>Benefits of Interceptors</strong></p><ul><li><strong>Clean Code:</strong> Less repetitive code, easier to read and understand.</li><li><strong>Reusability:</strong> The same interceptor can be used for multiple API calls.</li><li><strong>Error Handling:</strong> Centralized error handling for all API calls.</li><li><strong>Flexibility:</strong> You can add features like logging, authentication, and data caching to the interceptor.</li></ul><p><strong>Handling Errors</strong></p><p>Interceptors make error handling easier. In the examples above, we catch errors and either print them to the console or throw exceptions that can be handled by the calling code. You can customize this error handling based on your app’s requirements.</p><p><strong>Parsing Data</strong></p><p>The key is to use a parser to convert the data from the server into the format you need. In the examples, we’ve used JSON decoding to parse the data into arrays of strings. You can use other parsers depending on the data format.</p><p><strong>Key Takeaway</strong></p><p>Using network call interceptors in your declarative UI frameworks can significantly improve the organization and efficiency of your API interactions. By taking care of the repetitive tasks of making requests and handling responses, interceptors allow you to focus on the core logic of your app.</p><p>💙💙 Let me know if you see any areas where I can make this explanation even better! I’m always up for suggestions and improvements. 💙💙</p><p>Clap-clap-clap… clap-clap-clap… Keep clapping until you hit 10! 🎉</p><p>Want to take your Flutter knowledge to the next level? Check out my recent series on <a href="https://mukundjogi.hashnode.dev/series/flutter-interview">Flutter interview questions</a> for all levels. Get ready to impress in your next interview!</p><p>Let’s keep sharing, learning, and practicing! 🤘🏻</p><p><em>Originally published at </em><a href="https://mukundjogi.hashnode.dev/the-secret-to-easy-api-calls-interceptors-in-swiftui-compose-and-flutter"><em>https://mukundjogi.hashnode.dev</em></a><em> on November 11, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40c33fdd8e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative UI Power: How SwiftUI, Compose, and Flutter Handle Time-Sensitive Tasks]]></title>
            <link>https://medium.com/@mukundjogi/declarative-ui-power-how-swiftui-compose-and-flutter-handle-time-sensitive-tasks-60d109b5334e?source=rss-ea5224204e53------2</link>
            <guid isPermaLink="false">https://medium.com/p/60d109b5334e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mukund Jogi]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 10:12:41 GMT</pubDate>
            <atom:updated>2024-10-23T10:19:59.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-sV6EqsmcnSMswLl" /></figure><p>Hey, imagine you’re building a house. With a <em>declarative</em> approach, you don’t tell the builders to “hammer a nail here, then put a brick there.” Instead, you give them a blueprint. “Here’s how the house should look,” you say. The builders figure out how to get it done.</p><p>That’s the gist of declarative UI frameworks like SwiftUI, Compose, and Flutter. You describe what your UI should look like, and the framework handles the heavy lifting of rendering it on the screen.</p><p>Now, let’s talk about sync and async in this context. Think of it like getting ingredients for your house-building project.</p><p><strong>Synchronous:</strong></p><ul><li><strong>Imagine going to the store, picking up all the materials at once, and coming back to start building.</strong> It’s a straight-forward process.</li><li>In UI frameworks, synchronous operations happen immediately. If you tell the framework to update a text field, it happens right then and there. No waiting involved.</li></ul><p><strong>Asynchronous:</strong></p><ul><li><strong>Now imagine you need a special type of brick that needs to be custom-made. You order it, and the builder tells you, “I’ll let you know when it’s ready.”</strong> You have to wait for the brick, but you can still start working on other parts of the house while you wait.</li><li>This is like asynchronous tasks in UI frameworks. Fetching data from a network, loading images, or even complex calculations — they take time. So, the framework allows you to keep working on the UI while these tasks happen in the background.</li></ul><p><strong>Why is this important?</strong></p><p>Imagine you’re browsing a shopping app. You tap on a product, and the app needs to fetch details like the product description, price, and reviews. If this happens synchronously, your app freezes while it waits for the data. The user sees a blank screen, which is a terrible experience!</p><p>Asynchronous tasks save the day. The app can display a loading indicator, show the basic product information it already has, and fetch the rest of the data in the background. When the data arrives, it seamlessly updates the UI without interrupting the user.</p><p>Let’s see some examples:</p><p><strong>SwiftUI</strong></p><pre>// Synchronous:<br>Text(&quot;Hello, World!&quot;) // This will be rendered immediately<br><br>// Asynchronous (using a Task):<br>Task {<br>  let data = await fetchData()  // Fetch data from network<br>  Text(&quot;Data: \(data)&quot;) // Update the text when data is ready<br>}</pre><p><strong>Compose</strong></p><pre>// Synchronous:<br>Text(&quot;Hello, World!&quot;) //  Rendered right away<br><br>// Asynchronous (using a Coroutine):<br>LaunchedEffect(key1 = Unit) {<br>    val data = fetchData() // Fetch data from a network<br>    Text(&quot;Data: $data&quot;) // Update text after fetching data<br>}</pre><p><strong>Flutter</strong></p><pre>// Synchronous:<br>Text(&quot;Hello, World!&quot;) //  Rendered immediately<br><br>// Asynchronous (using async/await):<br>FutureBuilder&lt;String&gt;(<br>    future: fetchData(),<br>    builder: (context, snapshot) {<br>      if (snapshot.hasData) {<br>        return Text(&quot;Data: ${snapshot.data}&quot;);<br>      } else if (snapshot.hasError) {<br>        return Text(&#39;Error: ${snapshot.error}&#39;);<br>      } else {<br>        return CircularProgressIndicator();<br>      }<br>    },<br>);</pre><p><strong>Key takeaways:</strong></p><ul><li><strong>Declarative UI frameworks let you focus on what your UI should <em>look like</em>, not how to achieve it.</strong></li><li><strong>Synchronous tasks happen instantly, while asynchronous tasks can take time.</strong></li><li><strong>Managing async tasks in UI frameworks is crucial for smooth and responsive user experiences.</strong></li></ul><p>Think of it like building a house. You describe what you want, and the framework figures out the details, synchronously or asynchronously, to deliver a polished and functional home!</p><p><strong>Extra Tips:</strong></p><ul><li><strong>Avoid blocking the UI thread with long-running operations.</strong> Use asynchronous tasks to keep your app responsive.</li><li><strong>Think about the user experience.</strong> Provide appropriate loading indicators and error messages to keep the user informed while async tasks are running.</li><li><strong>Use built-in tools and libraries for managing async tasks.</strong> Each framework offers ways to handle asynchronous operations efficiently.</li></ul><p>By understanding the dance between synchronous and asynchronous tasks, you can create smooth and user-friendly apps with declarative UI frameworks. Remember, the goal is to deliver a seamless experience, even when dealing with tasks that take time!</p><p>💙💙 Let me know if you see any areas where I can make this explanation even better! I’m always up for suggestions and improvements. 💙💙</p><p>Clap-clap-clap… clap-clap-clap… Keep clapping until you hit 10! 🎉</p><p>Want to take your Flutter knowledge to the next level? Check out my recent series on <a href="https://mukundjogi.hashnode.dev/series/flutter-interview">Flutter interview questions</a> for all levels. Get ready to impress in your next interview!</p><p>Let’s keep sharing, learning, and practicing! 🤘🏻</p><p><em>Originally published at </em><a href="https://mukundjogi.hashnode.dev/sync-async-with-declarative-ui"><em>https://mukundjogi.hashnode.dev</em></a><em> on October 23, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d109b5334e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>