<?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 Pankaj Jangid on Medium]]></title>
        <description><![CDATA[Stories by Pankaj Jangid on Medium]]></description>
        <link>https://medium.com/@pankajjangid?source=rss-3c9992fed030------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2YVNShlxDYks9ZYunQtmCQ.png</url>
            <title>Stories by Pankaj Jangid on Medium</title>
            <link>https://medium.com/@pankajjangid?source=rss-3c9992fed030------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:05:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pankajjangid/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[The Android Security Hardening Checklist for Production Apps]]></title>
            <link>https://pankajjangid.medium.com/the-android-security-hardening-checklist-for-production-apps-f94f295283de?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94f295283de</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Fri, 15 May 2026 03:41:30 GMT</pubDate>
            <atom:updated>2026-05-15T03:41:30.075Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>**TL;DR**: Most Android apps protect the happy path and ignore everything else. This checklist covers build hardening, SSL pinning, the Keystore, Play Integrity, anti-instrumentation, and runtime UI defenses. Each section gives the working pattern, the common mistake, and one line of code. Tested at UOB TMRW scale, 3M+ users across four countries.</em></blockquote><p>When I shipped my first banking app, I thought the OAuth token in EncryptedSharedPreferences was the security story. It was not. The hardest attacks at UOB TMRW came from rooted devices, hooked binaries, and replayed network traffic. Not from password cracking.</p><p>Security on Android is a defense-in-depth problem. A determined attacker will get past any single layer. Your job is to make every layer cost more than the reward.</p><p>This is the checklist I now apply to every production release. Each item maps to a real incident I have seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUFwwE8TCTNO31_-6WoibA.png" /></figure><h3>Start With a Threat Model, Not a Library</h3><p>70% of security work happens before you write code. Pick what you are defending: user credentials, session tokens, API responses, business logic, intellectual property, or all of them. The defenses for “stop a casual MITM” differ from “stop a rooted attacker reverse engineering your auth flow.”</p><p>For a fintech app, my baseline list is:</p><ol><li>Token theft over the network</li><li>Token theft on the device</li><li>API replay and tampering</li><li>Reverse engineering of business rules</li><li>Account takeover on rooted devices</li><li>Overlay and screenshot capture of sensitive screens</li></ol><p>Write yours down. The checklist below maps to these threats one by one.</p><h3>Lock the Build</h3><p>A release APK that ships with debuggable=true is the single biggest own-goal in Android. Every internal field becomes inspectable through adb shell run-as. Block it at the build level.</p><pre>android {<br>    buildTypes {<br>        release {<br>            isMinifyEnabled = true<br>            isShrinkResources = true<br>            isDebuggable = false<br>            proguardFiles(<br>                getDefaultProguardFile(&quot;proguard-android-optimize.txt&quot;),<br>                &quot;proguard-rules.pro&quot;<br>            )<br>            signingConfig = signingConfigs.getByName(&quot;release&quot;)<br>        }<br>    }<br>}<br><br></pre><p>R8 is not optional. It strips unused code and renames symbols, which raises the cost of static analysis by an order of magnitude. Pair it with a proguard-rules.pro that keeps only what the framework requires, never -keep class **.</p><p>Lock cleartext traffic next. The network_security_config.xml is the canonical way:</p><pre>&lt;network-security-config&gt;<br>    &lt;base-config cleartextTrafficPermitted=&quot;false&quot;&gt;<br>        &lt;trust-anchors&gt;<br>            &lt;certificates src=&quot;system&quot; /&gt;<br>        &lt;/trust-anchors&gt;<br>    &lt;/base-config&gt;<br>&lt;/network-security-config&gt;<br><br></pre><p>Reference it from your manifest with android:networkSecurityConfig. Now any HTTP call without TLS throws at runtime, including the one your intern added to debug staging.</p><h3>SSL Pinning That Actually Works</h3><p>Pinning prevents a malicious CA from issuing a valid-looking certificate for your domain. The mistake I see most: pinning the leaf certificate. When that certificate rotates, every old install breaks.</p><p>Pin the <strong>subject public key info (SPKI) of an intermediate</strong>, and pin at least two backups. OkHttp makes this clean:</p><pre>val pinner = CertificatePinner.Builder()<br>    .add(&quot;api.yourbank.com&quot;,<br>        &quot;sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=&quot;,<br>        &quot;sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=&quot;)<br>    .build()<br><br>val client = OkHttpClient.Builder()<br>    .certificatePinner(pinner)<br>    .build()<br><br></pre><p>Two pins give you rotation without an emergency app update. Generate the hash using OpenSSL by piping the public key into a SHA-256 digest, then base64 encode the binary output.</p><p>Pinning alone is not enough. A rooted attacker can hook CertificatePinner.check with Frida. Pinning is the wall, root and hook detection is the trip wire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UbJrkSQBWx6yu2H-2bBkQ.png" /></figure><h3>Store Secrets in the Keystore, Not on Disk</h3><p>90% of “secure storage” code I review writes an AES key to a file and calls it done. The Keystore exists for one reason: keys never leave the hardware-backed security module on supported devices. Your app gets a handle. The bytes stay sealed.</p><pre>val masterKey = MasterKey.Builder(context)<br>    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>    .setUserAuthenticationRequired(true, 60)<br>    .build()<br><br>val prefs = EncryptedSharedPreferences.create(<br>    context,<br>    &quot;secure_session&quot;,<br>    masterKey,<br>    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>)<br><br></pre><p>The setUserAuthenticationRequired(true, 60) line is the one most people miss. It ties decryption to a biometric or device credential within the last 60 seconds. A thief with an unlocked device cannot read the data without authenticating.</p><p>Never store:</p><ul><li>Raw passwords (use refresh tokens issued by the server)</li><li>API keys that grant non-revocable access</li><li>PII that the server can return on demand</li></ul><p>What lives on the device should be revocable in one server call.</p><h3>Verify the Environment With Play Integrity</h3><p>The Play Integrity API is Google’s replacement for SafetyNet. It returns a signed verdict about the device, app, and account. Three fields matter:</p><ul><li>appIntegrity: the running APK matches the one signed by you</li><li>deviceIntegrity: the device passes basic OEM checks (rough proxy for &quot;not rooted&quot;)</li><li>appLicensingVerdict: the user obtained the app through Play</li></ul><p>Validation must happen on your server, not the client. A client-side check can be patched out in minutes.</p><pre>val integrityManager = IntegrityManagerFactory.create(context)<br>val nonce = generateNonceFromServer()<br><br>val request = IntegrityTokenRequest.builder()<br>    .setNonce(nonce)<br>    .build()<br><br>integrityManager.requestIntegrityToken(request)<br>    .addOnSuccessListener { response -&gt;<br>        // Send response.token() to your server for verification<br>        api.verifyIntegrity(response.token())<br>    }<br><br></pre><p>For high-value actions, like a money transfer, request a fresh token each time. The cost is one network round trip. The benefit is that emulators, rooted devices, and tampered binaries fail the check before the action goes through.</p><h3>Defend Against Instrumentation</h3><p>Frida hooks live functions at runtime. It is the tool of choice for bypassing pinning, jailbreak checks, and license verification. Detection is not bulletproof, but raising the cost matters.</p><p>Three cheap signals that catch lazy attackers:</p><pre>fun isFridaPortOpen(): Boolean {<br>    return try {<br>        Socket().use { socket -&gt;<br>            socket.connect(InetSocketAddress(&quot;127.0.0.1&quot;, 27042), 200)<br>            true<br>        }<br>    } catch (e: IOException) {<br>        false<br>    }<br>}<br><br>fun isDebuggerAttached(): Boolean =<br>    Debug.isDebuggerConnected() || Debug.waitingForDebugger()<br><br>fun isEmulator(): Boolean =<br>    Build.FINGERPRINT.contains(&quot;generic&quot;) ||<br>    Build.MODEL.contains(&quot;Emulator&quot;) ||<br>    Build.MANUFACTURER.contains(&quot;Genymotion&quot;)<br><br></pre><p>Combine these with Play Integrity. If five out of six signals are clean, allow the transaction. If three or more are dirty, log the event server-side and step up to biometric reauth.</p><p>Never crash the app on detection. Attackers will iterate until they find the exact signal that triggered the crash. Silent telemetry and server-side blocking is the better answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbtH9o9p8Ij_9y_hqXHZqg.png" /></figure><h3>Block Screenshots, Overlays, and Accessibility Abuse</h3><p>The OS gives you three switches that close common UI attacks:</p><pre>// Block screenshots and screen recording<br>window.setFlags(<br>    WindowManager.LayoutParams.FLAG_SECURE,<br>    WindowManager.LayoutParams.FLAG_SECURE<br>)<br><br>// Reject taps from overlays sitting on top of you<br>view.filterTouchesWhenObscured = true<br><br>// Hide accessibility tree on sensitive views<br>view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO<br><br></pre><p>FLAG_SECURE blocks screenshot apps and screen recording. filterTouchesWhenObscured rejects taps when another window covers yours, defeating overlay phishing. Accessibility services can read screen content, so we hide the accessibility tree on PIN entry and transfer confirmation only.</p><p>Apply these per-Activity, not globally. Customer support screenshots of error screens still need to work.</p><h3>Bind the Session to the Device</h3><p>A stolen refresh token should not survive a SIM swap. Bind the token to a device-specific key:</p><ol><li>On first login, generate a key pair in the Keystore with setUserAuthenticationRequired(true).</li><li>Send the public key to the server alongside the auth response.</li><li>For every subsequent token refresh, sign a server-issued challenge with the private key.</li></ol><p>If the attacker copies the refresh token to another device, the private key stays behind. The signature fails. The session dies.</p><p>This is the same model FIDO2 and WebAuthn use, and the Keystore makes it a 30-line implementation.</p><h3>Common Mistakes I See Every Sprint</h3><p>Even teams that ship the checklist above slip on the basics:</p><ul><li>Logging tokens to Crashlytics inside Interceptor.intercept(). Crash reports go to third-party servers.</li><li>Sharing a single API key across all builds. Rotate per environment.</li><li>Pinning the leaf certificate without a backup pin. Plan for rotation.</li><li>Calling Toast.makeText(this, exception.toString()) and leaking stack traces with internal class names.</li><li>Trusting client-side validation. Every check that matters runs on the server too.</li><li>Shipping BuildConfig.DEBUG = true in flavors that go to Play. Check ApplicationInfo.FLAG_DEBUGGABLE at runtime instead.</li></ul><h3>The Production Checklist</h3><p>Before any release to a production track, walk through this list and verify each item with a real device test:</p><ol><li>isDebuggable = false, R8 enabled, network security config present</li><li>SSL pinning with at least two intermediate SPKI pins</li><li>Sensitive data behind EncryptedSharedPreferences with setUserAuthenticationRequired</li><li>Play Integrity verified server-side for high-value actions</li><li>Frida, debugger, and emulator signals collected and reported</li><li>FLAG_SECURE on every screen showing balance, PIN, OTP, or transfer details</li><li>Session refresh tokens bound to a Keystore key pair</li><li>Server-side rate limiting on auth, OTP, and transfer endpoints</li><li>Crash reports sanitized of tokens and PII</li><li>Penetration test report from the last release reviewed and closed</li></ol><h3>Closing Thoughts</h3><p>Security is not a single feature you ship. It is the absence of incidents over time. Every item above came from a real incident, mine or a colleague’s. Treat the checklist as a forcing function: if you cannot tick every box, document why and revisit it next sprint.</p><p>In the 9 years I have spent on Android, security work pays the highest compounding return. One incident in production costs more than every defense above combined.</p><p><strong>Key takeaways:</strong></p><ul><li>Build hardening blocks 80% of casual attacks for free</li><li>Pin SPKI, not leaf certificates, and rotate with two pins</li><li>The Keystore is the only safe place for keys, treat the device as untrusted</li><li>Play Integrity is server-validated, never trust client-side verdicts</li><li>Frida detection is a deterrent, not a wall, layer it with server checks</li><li>FLAG_SECURE is one line and closes a whole class of UI attacks</li></ul><p>Apply the checklist, log the gaps, ship the release.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94f295283de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Find and Fix Memory Leaks in Android: A Practical Guide to LeakCanary]]></title>
            <link>https://pankajjangid.medium.com/how-to-find-and-fix-memory-leaks-in-android-a-practical-guide-to-leakcanary-e5c41f9a1d1c?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c41f9a1d1c</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 04:36:32 GMT</pubDate>
            <atom:updated>2026-04-06T04:36:32.394Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>**TL;DR**: Memory leaks caused 12% of our app’s ANRs before we implemented systematic detection. Using LeakCanary, we reduced memory-related crashes by 80% in three weeks. This guide shows the exact setup and workflow we use at UOB TMRW to catch leaks before they reach production.</em></blockquote><h3>Introduction</h3><p>Memory leaks are silent killers in Android apps. They do not crash your app immediately. Instead, they slowly consume available memory until the system forces a termination or the app becomes unresponsive.</p><p>At UOB TMRW, our 3M+ user fintech app was experiencing intermittent ANRs that traditional crash reporting could not explain. The root cause? Activity and Fragment references held by long-lived objects. One leaked Activity does not matter. A thousand do. After integrating LeakCanary into our debug workflow, we identified and fixed 47 distinct leak patterns in our first month of systematic detection.</p><p>This article walks through setting up LeakCanary for production-grade leak detection, interpreting heap dumps, and fixing the most common leak patterns in Android apps.</p><h3>Prerequisites</h3><ul><li>Android Studio Hedgehog or newer</li><li>Kotlin 1.9+</li><li>Familiarity with Activity/Fragment lifecycles</li><li>~20 minutes to implement the full workflow</li></ul><h3>Step 1: Add LeakCanary to Your Debug Build (5 minutes)</h3><p><strong>By the end of this step, you’ll have LeakCanary monitoring every Activity and Fragment for retained instances.</strong></p><p>LeakCanary runs only in debug builds. This is intentional. You do not want heap dumping in production. The library adds significant overhead during analysis, but the detection itself is lightweight.</p><p>Add the dependency to your build.gradle (Module: app):</p><pre>dependencies {<br>    // LeakCanary only for debug builds<br>    debugImplementation(&quot;com.squareup.leakcanary:leakcanary-android:2.13&quot;)<br>    <br>    // No-op for release builds (zero overhead)<br>    releaseImplementation(&quot;com.squareup.leakcanary:leakcanary-android-no-op:1.6.3&quot;)<br>}<br><br></pre><p><strong>Why separate dependencies?</strong> The no-op artifact provides identical APIs but does nothing in release builds. This prevents ClassNotFoundException without requiring ProGuard rules.</p><p><strong>Verification</strong>: Build and run your debug app. LeakCanary auto-installs. You should see a notification channel created on first launch. If you see the “LeakCanary” launcher icon, the integration worked.</p><h3>Step 2: Configure Detection Scope (5 minutes)</h3><p><strong>By the end of this step, LeakCanary will watch your custom objects and background components, not just Activities.</strong></p><p>The default configuration watches Activities and Fragments. Most production apps need broader coverage.</p><p>Create a custom Application class:</p><pre>class MyApplication : Application() {<br>    <br>    override fun onCreate() {<br>        super.onCreate()<br>        <br>        if (BuildConfig.DEBUG) {<br>            configureLeakCanary()<br>        }<br>    }<br>    <br>    private fun configureLeakCanary() {<br>        val config = LeakCanary.config.copy(<br>            // Watch custom objects beyond Activities<br>            watchDurationMillis = 20_000, // 20 seconds<br>            // Trigger heap dump at 5 retained instances<br>            retainedVisibleThreshold = 5,<br>            // Run analysis on separate process<br>            computeRetainedHeapSize = true<br>        )<br>        <br>        LeakCanary.config = config<br>        <br>        // Watch specific objects manually<br>        AppWatcher.objectWatcher.watch(<br>            watchedObject = this,<br>            description = &quot;Application instance should not be retained&quot;<br>        )<br>    }<br>}<br><br></pre><p><strong>Key configuration values explained:</strong></p><ul><li>watchDurationMillis: How long to wait before considering an object retained. Default is 5 seconds. Increase this if you have legitimate long-running operations.</li><li>retainedVisibleThreshold: Number of retained instances before triggering a heap dump. Lower values detect leaks faster but dump more frequently.</li></ul><p><strong>Verification</strong>: Launch your app. Check Logcat for LeakCanary tag messages. You should see Watching instance of logs for your Application class.</p><h3>Step 3: Watch Background Components (8 minutes)</h3><p><strong>By the end of this step, ViewModels, Services, and singleton holders will be monitored for leaks.</strong></p><p>Activities and Fragments are easy. The real leaks hide in ViewModels, Services, and custom lifecycle owners.</p><h3>Watching ViewModels</h3><p>ViewModels outlive configuration changes but should not outlive their scope. Watch them in your base ViewModel:</p><pre>abstract class BaseViewModel : ViewModel() {<br>    <br>    init {<br>        if (BuildConfig.DEBUG) {<br>            AppWatcher.objectWatcher.watch(<br>                watchedObject = this,<br>                description = &quot;${this::class.java.simpleName} should be cleared after use&quot;<br>            )<br>        }<br>    }<br>    <br>    override fun onCleared() {<br>        super.onCleared()<br>        // LeakCanary will report if this ViewModel is still retained<br>    }<br>}<br><br></pre><h3>Watching Services and Receivers</h3><pre>class PaymentSyncService : Service() {<br>    <br>    override fun onCreate() {<br>        super.onCreate()<br>        <br>        AppWatcher.objectWatcher.watch(<br>            watchedObject = this,<br>            description = &quot;PaymentSyncService should be destroyed after job completion&quot;<br>        )<br>    }<br>    <br>    override fun onBind(intent: Intent?): IBinder? = null<br>    <br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>        // Your background work<br>        return START_NOT_STICKY<br>    }<br>}<br><br></pre><h3>Watching Custom Objects</h3><p>The most common leak source: singleton managers holding references to Views or Activities.</p><pre>object AnalyticsManager {<br>    private var currentActivity: Activity? = null<br>    <br>    fun trackScreen(activity: Activity) {<br>        // DANGER: This creates a leak<br>        // currentActivity = activity<br>        <br>        // SAFE: Use WeakReference<br>        currentActivityRef = WeakReference(activity)<br>        <br>        // Or better: extract what you need immediately<br>        val screenName = activity::class.java.simpleName<br>        trackEvent(&quot;screen_view&quot;, mapOf(&quot;name&quot; to screenName))<br>    }<br>    <br>    private var currentActivityRef: WeakReference&lt;Activity&gt;? = null<br>}<br><br></pre><p><strong>Verification</strong>: Trigger a configuration change (rotate device) while these components are active. Check Logcat for retention warnings.</p><h3>Step 4: Reading LeakCanary Reports (5 minutes)</h3><p><strong>By the end of this step, you’ll interpret heap dump reports and identify root causes.</strong></p><p>When LeakCanary detects a leak, it shows a notification. Tap it to see the leak trace.</p><h3>Anatomy of a Leak Trace</h3><pre>┬───<br>│ GC Root: System class<br>│<br>├─ android.provider.FontsContract class<br>│    Leaking: NO (a class is never leaking)<br>│    ↓ static FontsContract.sContext<br>│                    ~~~~~~~~<br>├─ com.example.app.MainActivity instance<br>│    Leaking: YES (Activity#mDestroyed is true)<br>│    ↓ MainActivity.textWatcher<br>│                   ~~~~~~~~~~~~<br>╰→ androidx.appcompat.widget.AppCompatEditText instance<br>     Leaking: YES (View detached and has parent)<br><br></pre><p><strong>How to read this:</strong></p><ol><li><strong>GC Root</strong>: Where the garbage collector starts. Cannot be collected.</li><li><strong>Arrows (↓)</strong>: Reference chain from root to leaked object</li><li><strong>Leaking: YES/NO</strong>: Whether this object is part of the leak</li><li><strong>Final object</strong>: The actual leaked instance</li></ol><h3>Common Leak Patterns</h3><p><strong>Pattern 1: Anonymous Inner Classes</strong></p><pre>// LEAK: Anonymous inner class holds reference to outer Activity<br>button.setOnClickListener {<br>    // &#39;this&#39; inside here references the Activity<br>    handler.postDelayed({<br>        updateUI() // Activity reference leaked for 5 seconds<br>    }, 5000)<br>}<br><br>// FIX: Use static nested class or remove callback<br>class MyActivity : AppCompatActivity() {<br>    private val handler = Handler(Looper.getMainLooper())<br>    private val updateRunnable = Runnable { updateUI() }<br>    <br>    override fun onDestroy() {<br>        super.onDestroy()<br>        handler.removeCallbacks(updateRunnable)<br>    }<br>}<br><br></pre><p><strong>Pattern 2: Singleton Holding Context</strong></p><pre>// LEAK: Singleton lives forever, holds Activity forever<br>object DatabaseHelper {<br>    private lateinit var context: Context<br>    <br>    fun init(ctx: Context) {<br>        context = ctx // Never garbage collected<br>    }<br>}<br><br>// FIX: Use Application context<br>fun init(ctx: Context) {<br>    context = ctx.applicationContext // OK: App context lives forever anyway<br>}<br><br></pre><p><strong>Pattern 3: RxJava Disposables</strong></p><pre>class UserViewModel : BaseViewModel() {<br>    private val disposables = CompositeDisposable()<br>    <br>    fun loadUser() {<br>        userRepository.getUser()<br>            .subscribeOn(Schedulers.io())<br>            .observeOn(AndroidSchedulers.mainThread())<br>            .subscribe { user -&gt;<br>                // If ViewModel is cleared but this completes,<br>                // and user references a View...<br>            }<br>            .addTo(disposables)<br>    }<br>    <br>    override fun onCleared() {<br>        disposables.clear() // Essential: prevents leaks<br>    }<br>}<br><br></pre><p><strong>Pattern 4: TextWatcher and Listeners</strong></p><pre>override fun onDestroyView() {<br>    super.onDestroyView()<br>    // Remove listeners that might hold View references<br>    editText.removeTextChangedListener(textWatcher)<br>    button.setOnClickListener(null)<br>}<br><br></pre><h3>Step 5: Production Monitoring Without LeakCanary (7 minutes)</h3><p><strong>By the end of this step, you’ll track memory growth in production builds without heap dumping.</strong></p><p>LeakCanary is debug-only. For production, monitor memory metrics through Firebase or similar.</p><pre>class MemoryMonitor(private val context: Context) {<br>    <br>    private val runtime = Runtime.getRuntime()<br>    <br>    fun logMemoryStats() {<br>        val usedMem = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024<br>        val maxMem = runtime.maxMemory() / 1024 / 1024<br>        val percentUsed = (usedMem * 100 / maxMem)<br>        <br>        // Log to Firebase Analytics<br>        Firebase.analytics.logEvent(&quot;memory_status&quot;) {<br>            param(&quot;used_mb&quot;, usedMem.toLong())<br>            param(&quot;max_mb&quot;, maxMem.toLong())<br>            param(&quot;percent_used&quot;, percentUsed.toLong())<br>        }<br>        <br>        // Alert if usage exceeds threshold<br>        if (percentUsed &gt; 85) {<br>            reportHighMemoryUsage(percentUsed)<br>        }<br>    }<br>    <br>    private fun reportHighMemoryUsage(percent: Long) {<br>        // Send to Crashlytics as non-fatal<br>        val exception = RuntimeException(&quot;High memory usage: ${percent}%&quot;)<br>        Firebase.crashlytics.recordException(exception)<br>    }<br>}<br><br></pre><p>Schedule periodic checks:</p><pre>// In Application.onCreate()<br>val workRequest = PeriodicWorkRequestBuilder&lt;MemoryCheckWorker&gt;(<br>    1, TimeUnit.HOURS<br>).build()<br><br>WorkManager.getInstance(this).enqueueUniquePeriodicWork(<br>    &quot;memory_monitor&quot;,<br>    ExistingPeriodicWorkPolicy.KEEP,<br>    workRequest<br>)<br><br></pre><h3>Common Mistakes to Avoid</h3><p><strong>Holding View references in ViewModels</strong></p><p>ViewModels outlive configuration changes but should not reference Views. The ViewModel survives while the old Activity dies. If the ViewModel holds a TextView reference, that TextView (and its entire view hierarchy) leaks.</p><p><strong>Using Activity context for Toast outside of Activity</strong></p><pre>// LEAK<br>Toast.makeText(activity, &quot;Message&quot;, Toast.LENGTH_LONG).show()<br><br>// SAFE<br>Toast.makeText(activity.applicationContext, &quot;Message&quot;, Toast.LENGTH_LONG).show()<br><br></pre><p><strong>Forgot to unregister BroadcastReceivers</strong></p><pre>override fun onStart() {<br>    super.onStart()<br>    registerReceiver(receiver, IntentFilter(ACTION))<br>}<br><br>override fun onStop() {<br>    super.onStop()<br>    unregisterReceiver(receiver) // Essential<br>}<br><br></pre><p><strong>Holding Fragment references in Adapters</strong></p><p>RecyclerView Adapters should never hold direct Fragment references. Use interfaces or lambda callbacks instead.</p><h3>Key Takeaways</h3><ul><li>Memory leaks accumulate. One leaked Activity is fine. A thousand will kill your app.</li><li>LeakCanary is debug-only by design. It adds overhead you do not want in production.</li><li>The most common leaks: anonymous inner classes, static context holders, and forgotten listeners</li><li>Always remove callbacks and listeners in lifecycle teardown methods</li><li>Monitor memory in production using Runtime metrics, not heap dumps</li></ul><h3>Next Steps</h3><ol><li>Add LeakCanary to your debug build today</li><li>Watch one ViewModel and one Service this week</li><li>Fix the first leak you find. The pattern likely repeats elsewhere.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c41f9a1d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android App Startup Optimization: From 3.2s to 1.1s Cold Start]]></title>
            <link>https://pankajjangid.medium.com/android-app-startup-optimization-from-3-2s-to-1-1s-cold-start-507e3c376573?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/507e3c376573</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 11:17:13 GMT</pubDate>
            <atom:updated>2026-03-28T11:17:13.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51yUoqeGhXNKe14rvNcm-w.png" /></figure><p><em>Practical techniques that cut our fintech app’s startup time by 65%, with real profiler data</em></p><p><strong>TL;DR:</strong> Cold start time is the first impression your app makes. We reduced UOB TMRW’s cold start from 3.2 seconds to 1.1 seconds using 5 techniques: lazy ContentProvider initialization, Baseline Profiles, background thread bootstrapping, App Startup Library, and removing reflection-heavy SDKs from the critical path. Here’s exactly how each one contributed.</p><h3>What Actually Happens During Cold Start</h3><p><strong>Cold start involves 4 phases, and most developers only optimize the last one.</strong> The system does heavy work before your code even runs, and some of that work is triggered by your app’s configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvNjC3DvViGQDs73jZOV1Q.png" /></figure><p>Here’s the full sequence:</p><p><strong>Phase 1: Process creation.</strong> Zygote forks a new process for your app. This takes 50–150ms and you can’t optimize it. It’s the OS allocating memory and setting up the ART runtime for your process.</p><p><strong>Phase 2: Application initialization.</strong> The system creates your Application object and calls onCreate(). This is where most startup time hides. Every ContentProvider, SDK initializer, and Dagger component graph builds here.</p><p><strong>Phase 3: Activity creation.</strong> Your launcher Activity’s onCreate(), onStart(), and onResume() run. Layout inflation, view binding, and initial data fetching happen here.</p><p><strong>Phase 4: First frame render.</strong> The system measures, lays out, and draws your first frame. The cold start “ends” when the first frame finishes rendering. Anything that delays this frame directly impacts the user’s perception of speed.</p><p>At UOB TMRW, we profiled each phase using Android Studio’s CPU Profiler and found that Phase 2 consumed 1.8 seconds out of the 3.2-second total. Application.onCreate() was the bottleneck.</p><h3>The Biggest Hidden Cost: ContentProviders</h3><p><strong>ContentProviders initialize BEFORE Application.onCreate(), and every SDK that registers one adds to your startup time.</strong> Firebase alone registers 5 ContentProviders. WorkManager registers one. Crash reporting tools, analytics SDKs, and ad libraries each add their own.</p><p>Here’s how we discovered the problem. We added a simple timing log:</p><pre>class MyApp : Application() {<br>    override fun attachBaseContext(base: Context?) {<br>        val start = SystemClock.elapsedRealtime()<br>        super.attachBaseContext(base)<br>        Log.d(&quot;Startup&quot;, &quot;attachBaseContext done: ${SystemClock.elapsedRealtime() - start}ms&quot;)<br>    }<br><br>    override fun onCreate() {<br>        val start = SystemClock.elapsedRealtime()<br>        super.onCreate()<br>        Log.d(&quot;Startup&quot;, &quot;super.onCreate done: ${SystemClock.elapsedRealtime() - start}ms&quot;)<br>        // ... rest of init<br>    }<br>}<br><br></pre><p>The gap between attachBaseContext completing and onCreate starting was 800ms. That entire gap was ContentProvider initialization. The system iterates through every ContentProvider declared in the merged manifest and calls their onCreate() method sequentially, on the main thread.</p><h3>Technique 1: App Startup Library</h3><p><strong>The Jetpack App Startup Library replaces automatic ContentProvider initialization with a single ContentProvider that lazily initializes components on demand.</strong> This cut 600ms from our startup.</p><p>Instead of each SDK registering its own ContentProvider:</p><pre>// Before: each SDK auto-initializes via its own ContentProvider<br>// Firebase: 5 ContentProviders (~200ms)<br>// WorkManager: 1 ContentProvider (~150ms)<br>// Analytics: 1 ContentProvider (~100ms)<br>// Total: ~450ms just from ContentProvider.onCreate() calls<br><br></pre><p>We consolidated using App Startup:</p><pre>class WorkManagerInitializer : Initializer&lt;WorkManager&gt; {<br>    override fun create(context: Context): WorkManager {<br>        val config = Configuration.Builder()<br>            .setMinimumLoggingLevel(Log.INFO)<br>            .build()<br>        WorkManager.initialize(context, config)<br>        return WorkManager.getInstance(context)<br>    }<br><br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = emptyList()<br>}<br><br>class AnalyticsInitializer : Initializer&lt;Analytics&gt; {<br>    override fun create(context: Context): Analytics {<br>        return Analytics.init(context, BuildConfig.ANALYTICS_KEY)<br>    }<br><br>    // Analytics depends on WorkManager for event batching<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; =<br>        listOf(WorkManagerInitializer::class.java)<br>}<br><br></pre><p>Then in the manifest, we disabled the default ContentProviders and registered a single InitializationProvider:</p><pre>&lt;!-- Disable WorkManager auto-init ContentProvider --&gt;<br>&lt;provider<br>    android:name=&quot;androidx.work.impl.WorkManagerInitializer&quot;<br>    android:authorities=&quot;${applicationId}.workmanager-init&quot;<br>    tools:node=&quot;remove&quot; /&gt;<br><br>&lt;!-- Disable Firebase&#39;s auto-init --&gt;<br>&lt;provider<br>    android:name=&quot;com.google.firebase.provider.FirebaseInitProvider&quot;<br>    android:authorities=&quot;${applicationId}.firebaseinitprovider&quot;<br>    tools:node=&quot;remove&quot; /&gt;<br><br></pre><p>The App Startup library runs all initializers through a single ContentProvider with dependency resolution. Components initialize in the correct order, but only one ContentProvider creation overhead exists instead of 7.</p><h3>Technique 2: Background Thread Bootstrapping</h3><p><strong>Move everything that doesn’t need the main thread off the main thread.</strong> This sounds obvious, but most SDK initialization happens on the main thread by default, even when it doesn’t need to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdSrC3Lm4WzKEFuiZZ3IqQ.png" /></figure><p>We split Application.onCreate() into two paths:</p><pre>class MyApp : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br><br>        // MAIN THREAD: only what must be here<br>        initCrashReporting()  // Must be first, catches crashes during init<br>        initDaggerGraph()     // UI depends on this immediately<br><br>        // BACKGROUND: everything else<br>        Executors.newFixedThreadPool(2).apply {<br>            submit { initFirebaseAnalytics() }<br>            submit { initNetworkClient() }<br>            submit { prefetchUserSession() }<br>            submit { warmUpImageLoader() }<br>        }<br>    }<br>}<br><br></pre><p>The rule is simple: if the launcher Activity’s first frame doesn’t depend on it, move it to a background thread. Firebase Analytics doesn’t need to finish before the splash screen shows. The network client doesn’t need to exist until the first API call.</p><p>This saved us 400ms because Retrofit’s OkHttpClient initialization, certificate pinning setup, and interceptor chain creation were all running on the main thread for no reason.</p><h3>Watch out for thread safety</h3><p>Some SDKs assume they’re initialized on the main thread. Firebase Crashlytics, for example, must be called from the main thread. Always check the SDK documentation before moving initialization off-main. We caught two race conditions during testing where background-initialized singletons were accessed before initialization completed.</p><p>The fix was a simple CountDownLatch for critical path dependencies:</p><pre>private val networkReady = CountDownLatch(1)<br><br>// Background thread<br>submit {<br>    initNetworkClient()<br>    networkReady.countDown()<br>}<br><br>// When first API call happens (any thread)<br>fun getApiClient(): ApiClient {<br>    networkReady.await(5, TimeUnit.SECONDS)<br>    return apiClient<br>}<br><br></pre><h3>Technique 3: Baseline Profiles</h3><p><strong>Baseline Profiles pre-compile your app’s hot code paths during installation, eliminating JIT compilation during the first run.</strong> This reduced our first-frame render time by 30%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNBowUJHhHp02XJFl-AeYQ.png" /></figure><p>Without Baseline Profiles, ART interprets your code on the first run, then JIT-compiles methods that get called frequently. The first cold start is always the slowest because nothing is compiled yet.</p><p>Baseline Profiles tell ART which methods to compile ahead of time:</p><pre>// benchmark/src/main/java/BaselineProfileGenerator.kt<br>@OptIn(ExperimentalBaselineProfilesApi::class)<br>@RunWith(AndroidJUnit4::class)<br>class BaselineProfileGenerator {<br><br>    @get:Rule<br>    val rule = BaselineProfileRule()<br><br>    @Test<br>    fun generateProfile() {<br>        rule.collect(&quot;com.uob.tmrw&quot;) {<br>            // Cold start flow<br>            startActivityAndWait()<br><br>            // Critical user journey: login -&gt; accounts -&gt; transfer<br>            device.findObject(By.res(&quot;login_button&quot;)).click()<br>            device.waitForIdle()<br><br>            device.findObject(By.res(&quot;accounts_tab&quot;)).click()<br>            device.waitForIdle()<br><br>            device.findObject(By.res(&quot;transfer_button&quot;)).click()<br>            device.waitForIdle()<br>        }<br>    }<br>}<br><br></pre><p>The generated profile covers Compose rendering, navigation setup, Dagger injection, and the most-used screens. Google Play distributes these profiles with your APK, and ART compiles the listed methods during installation.</p><h3>Measuring the impact</h3><p>We measured cold start before and after Baseline Profiles using adb shell am start-activity -W:</p><p><strong>Before Baseline Profiles:</strong> Average cold start across 10 runs: 1.6s (after other optimizations)</p><p><strong>After Baseline Profiles:</strong> Average cold start across 10 runs: 1.1s (31% improvement)</p><p>The impact is largest on the first launch after install or update. Subsequent launches benefit from JIT caching, so the difference narrows over time.</p><h3>Technique 4: Lazy Dagger Component Initialization</h3><p><strong>Don’t build your entire Dagger object graph at startup. Build only what the launcher screen needs.</strong> Our Dagger graph had 200+ bindings, and building it took 350ms.</p><p>We split the graph into an AppComponent (core bindings) and feature-scoped components that initialize on first access:</p><pre>@Singleton<br>@Component(modules = [CoreModule::class, NetworkModule::class])<br>interface AppComponent {<br>    fun loginComponentFactory(): LoginComponent.Factory<br>    fun accountsComponentFactory(): AccountsComponent.Factory<br>    // Feature components created lazily, not at startup<br>}<br><br>// In Application.onCreate()<br>val appComponent = DaggerAppComponent.builder()<br>    .coreModule(CoreModule(this))<br>    .build()<br>// Only core + network bindings are created (~80ms instead of 350ms)<br><br></pre><p>The LoginComponent is built when the login screen opens. The AccountsComponent when accounts are loaded. Each feature component adds 30–50ms when first accessed, but that happens after the app is already visible. The user sees a fast splash screen instead of staring at a white screen for 350ms.</p><h3>Technique 5: Remove Reflection from the Critical Path</h3><p><strong>Gson, Moshi (reflection adapter), and some DI frameworks use reflection at startup, which is slow on Android.</strong> We switched hot paths from Gson to Moshi with codegen adapters, cutting JSON parsing initialization from 120ms to 15ms.</p><pre>// Before: Gson uses reflection to inspect every field at first parse<br>val gson = Gson()<br>val user = gson.fromJson(json, User::class.java) // ~120ms first call<br><br>// After: Moshi codegen generates adapters at compile time<br>@JsonClass(generateAdapter = true)<br>data class User(<br>    val id: String,<br>    val name: String,<br>    val accounts: List&lt;Account&gt;<br>)<br>val moshi = Moshi.Builder().build()<br>val user = moshi.adapter(User::class.java).fromJson(json) // ~15ms first call<br><br></pre><p>Moshi’s codegen adapter generates a UserJsonAdapter class at compile time. No reflection, no field scanning, no annotation processing at runtime. The adapter is a plain Kotlin class with direct field access.</p><h3>The Full Results</h3><p>Here’s what each technique contributed to the total 65% reduction:</p><p><strong>ContentProvider consolidation (App Startup):</strong> 3.2s → 2.6s (-600ms)</p><p><strong>Background thread bootstrapping:</strong> 2.6s → 2.2s (-400ms)</p><p><strong>Lazy Dagger component initialization:</strong> 2.2s → 1.9s (-270ms)</p><p><strong>Remove reflection (Gson → Moshi codegen):</strong> 1.9s → 1.6s (-105ms)</p><p><strong>Baseline Profiles:</strong> 1.6s → 1.1s (-500ms)</p><p><strong>Total: 3.2s → 1.1s (65% reduction)</strong></p><p>The order matters. We tackled the biggest wins first (ContentProvider, Baseline Profiles) and the smaller wins last (reflection removal). Each technique was measured independently using adb shell am start-activity -W averaged over 10 runs on a mid-range device (Samsung Galaxy A52).</p><h3>Conclusion</h3><p>App startup optimization is about removing work from the critical path, not making work faster. Most of the 2.1 seconds we saved came from code that was running on the main thread but didn’t need to be there.</p><p><strong>Key takeaways:</strong></p><ul><li>Profile first. Don’t guess which phase is slow. Use CPU Profiler to find the real bottleneck.</li><li>ContentProviders are the hidden cost. Audit your merged manifest for auto-initializing SDKs.</li><li>Background thread everything that the first frame doesn’t need.</li><li>Baseline Profiles give you 20–30% improvement for free after other optimizations.</li><li>Lazy component initialization beats eager graph construction every time.</li></ul><p>Start with adb shell am start-activity -W on your app right now. If cold start is over 1.5 seconds, you have optimization opportunities hiding in Application.onCreate().</p><p><strong>Tags</strong>: Android, Performance, Kotlin, Mobile Development, App Optimization</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507e3c376573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Testing That Actually Catches Bugs: A Practical Strategy]]></title>
            <link>https://pankajjangid.medium.com/android-testing-that-actually-catches-bugs-a-practical-strategy-36e9c398578b?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e9c398578b</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 12:07:43 GMT</pubDate>
            <atom:updated>2026-03-16T12:07:43.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0IuvZhwmtPhtBVTgV5Oew.png" /></figure><p><em>What I learned testing a fintech app used by 3M+ people across 4 countries</em></p><p><strong>TL;DR:</strong> Most Android test suites catch syntax errors, not real bugs. After implementing a focused testing strategy on UOB TMRW (3M+ users, 96% crash-free), we found that 80% of production bugs came from 3 areas: ViewModel state transitions, API error handling, and navigation edge cases. Here’s the strategy that works.</p><h3>Introduction</h3><p><strong>Our crash-free rate jumped from 93.2% to 96% after we stopped writing tests for the sake of coverage and started testing what actually breaks.</strong> That 2.8% improvement sounds small until you realize it means 84,000 fewer crashes per month across 3M users.</p><p>The problem with most Android test suites isn’t that they’re missing. It’s that they test the wrong things. I’ve seen codebases with 70% coverage that still ship broken features because the tests verify that a button exists, not that it handles a timeout correctly.</p><p>This article covers the testing strategy we built for UOB TMRW, a fintech app serving users across Thailand, Singapore, Malaysia, and Indonesia. The principles work for any Android app, but the stakes in fintech made us ruthlessly practical about what to test and what to skip.</p><h3>The Testing Pyramid That Actually Works</h3><p><strong>The standard testing pyramid (unit &gt; integration &gt; UI) misleads Android developers because it doesn’t account for where bugs actually live.</strong> In our experience, most production crashes came from the space between layers, not within them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLKPV_0t61MkgRnEopaKDQ.png" /></figure><p>Here’s what we found after analyzing 6 months of production crashes:</p><p><strong>ViewModel + UseCase layer:</strong> 45% of all bugs. State transitions, error handling, and race conditions between coroutine scopes.</p><p><strong>API integration:</strong> 30% of bugs. Unexpected response shapes, timeout handling, token refresh failures during concurrent requests.</p><p><strong>Navigation edge cases:</strong> 15% of bugs. Deep links into expired sessions, back stack corruption after process death, fragment transaction timing.</p><p><strong>UI rendering:</strong> 10% of bugs. Mostly Compose recomposition issues and list adapter edge cases.</p><p>This means our testing effort should roughly match: heavy ViewModel testing, solid API integration tests, targeted navigation tests, and minimal UI tests.</p><h3>Unit Testing ViewModels: Where Most Bugs Hide</h3><p><strong>Every ViewModel should have tests for its state transitions, not just its initial state.</strong> The bug is rarely “the ViewModel doesn’t emit data.” It’s usually “the ViewModel emits the wrong state when the API call fails while a refresh is already in progress.”</p><p>Here’s our standard ViewModel test pattern:</p><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>class TransferViewModelTest {<br><br>    @get:Rule<br>    val mainDispatcherRule = MainDispatcherRule()<br><br>    private lateinit var viewModel: TransferViewModel<br>    private val repository = FakeTransferRepository()<br><br>    @Before<br>    fun setup() {<br>        viewModel = TransferViewModel(<br>            transferUseCase = TransferUseCase(repository),<br>            savedStateHandle = SavedStateHandle(<br>                mapOf(&quot;fromAccountId&quot; to &quot;ACC-001&quot;)<br>            )<br>        )<br>    }<br><br>    @Test<br>    fun `transfer fails gracefully on network timeout`() = runTest {<br>        // Arrange: simulate timeout<br>        repository.setShouldTimeout(true)<br><br>        // Act<br>        viewModel.executeTransfer(amount = 1000.0)<br><br>        // Assert: should show error, not crash<br>        val state = viewModel.uiState.first()<br>        assertIs&lt;TransferUiState.Error&gt;(state)<br>        assertEquals(&quot;Network timeout&quot;, state.message)<br>        assertFalse(state.isRetrying)<br>    }<br><br>    @Test<br>    fun `concurrent refresh does not duplicate API calls`() = runTest {<br>        viewModel.refreshBalance()<br>        viewModel.refreshBalance() // duplicate call<br><br>        // Only one API call should have been made<br>        assertEquals(1, repository.refreshCallCount)<br>    }<br>}<br><br></pre><h3>What to test in every ViewModel</h3><p><strong>Happy path:</strong> Data loads and emits correct UiState. This is the baseline.</p><p><strong>Error states:</strong> Network failure, server error (500), invalid response, token expired. Each should produce a specific UiState, not a crash.</p><p><strong>Race conditions:</strong> User taps submit twice, refresh triggered while another request is in-flight, screen rotated during API call.</p><p><strong>Process death:</strong> State restoration via SavedStateHandle. User input, selected items, and scroll position should survive recreate().</p><p><strong>Edge case data:</strong> Empty lists, null values from API, extremely long strings, special characters in user input. These trip up UI rendering and database queries more often than you’d expect. At UOB TMRW, we had a crash caused by a Thai bank account name containing special Unicode characters that broke our text truncation logic.</p><h3>Integration Testing with Real Room Database</h3><p><strong>Mocking the database in tests is how bugs slip into production undetected.</strong> The mock passes but the actual SQL query has a typo, a missing migration, or a wrong column name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyR1xN-jpQkMazJ7HeqNIA.png" /></figure><p>We use Robolectric with an in-memory Room database for integration tests. It’s fast (runs on JVM, not emulator) and catches real SQL issues:</p><pre>@RunWith(RobolectricTestRunner::class)<br>class AccountRepositoryIntegrationTest {<br><br>    private lateinit var db: AppDatabase<br>    private lateinit var dao: AccountDao<br>    private lateinit var repository: AccountRepositoryImpl<br><br>    @Before<br>    fun setup() {<br>        db = Room.inMemoryDatabaseBuilder(<br>            ApplicationProvider.getApplicationContext(),<br>            AppDatabase::class.java<br>        ).allowMainThreadQueries().build()<br><br>        dao = db.accountDao()<br>        repository = AccountRepositoryImpl(<br>            dao = dao,<br>            api = FakeAccountApi()<br>        )<br>    }<br><br>    @After<br>    fun teardown() {<br>        db.close()<br>    }<br><br>    @Test<br>    fun `sync updates local cache and returns fresh data`() = runTest {<br>        // Pre-populate with stale data<br>        dao.insert(AccountEntity(id = &quot;ACC-001&quot;, balance = 1000.0))<br><br>        // API returns updated balance<br>        (repository as AccountRepositoryImpl).api<br>            .setResponse(AccountDto(id = &quot;ACC-001&quot;, balance = 1500.0))<br><br>        // Sync should update local cache<br>        val result = repository.syncAndGetAccount(&quot;ACC-001&quot;)<br><br>        assertEquals(1500.0, result.balance, 0.01)<br>        assertEquals(1500.0, dao.getById(&quot;ACC-001&quot;)?.balance ?: 0.0, 0.01)<br>    }<br>}<br><br></pre><h3>Why not mock the database</h3><p>In our first year, we had 3 production bugs caused by Room migration failures that mocked tests never caught. One migration renamed a column, but the query still referenced the old name. The mock had no schema, so it passed. The real database threw SQLiteException at runtime.</p><p>Rule: if your test involves data persistence, use a real (in-memory) database.</p><h3>API Error Handling Tests</h3><p><strong>Every API endpoint should have tests for at least 5 failure modes, not just success.</strong> In fintech, a poorly handled 401 during a transfer can lock a user out of their account.</p><pre>class TransferApiTest {<br><br>    private val mockWebServer = MockWebServer()<br>    private lateinit var api: TransferApi<br><br>    @Before<br>    fun setup() {<br>        api = Retrofit.Builder()<br>            .baseUrl(mockWebServer.url(https://medium.com/&quot;/&quot;))<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>            .create(TransferApi::class.java)<br>    }<br><br>    @Test<br>    fun `handles 401 without crashing transfer flow`() = runTest {<br>        mockWebServer.enqueue(MockResponse().setResponseCode(401))<br><br>        val result = runCatching { api.executeTransfer(TransferRequest()) }<br><br>        assertTrue(result.isFailure)<br>        assertIs&lt;HttpException&gt;(result.exceptionOrNull())<br>    }<br><br>    @Test<br>    fun `handles malformed JSON response`() = runTest {<br>        mockWebServer.enqueue(<br>            MockResponse()<br>                .setBody(&quot;{invalid json&quot;)<br>                .setResponseCode(200)<br>        )<br><br>        val result = runCatching { api.getBalance(&quot;ACC-001&quot;) }<br><br>        assertTrue(result.isFailure)<br>    }<br>}<br><br></pre><h3>The 5 failure modes every endpoint needs</h3><p><strong>Timeout:</strong> Server doesn’t respond within the configured window.</p><p><strong>Auth failure (401/403):</strong> Token expired mid-session. Should trigger token refresh, not a crash.</p><p><strong>Server error (500):</strong> Backend is down. UI should show retry option.</p><p><strong>Malformed response:</strong> Backend returns unexpected JSON shape. Gson/Moshi should fail gracefully.</p><p><strong>Network gone:</strong> Airplane mode or tunnel. Should show offline state immediately.</p><h3>Testing in a Multi-Module Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoP3AUh3EqzcXD5OmfdvNw.png" /></figure><p><strong>Each feature module should have its own self-contained test suite that runs in under 30 seconds.</strong> At UOB TMRW with 8+ feature modules, running the full test suite takes 4+ minutes. But running :feature:payments:test takes 8 seconds. That fast feedback loop is why developers actually write tests.</p><h3>Module test boundaries</h3><p><strong>:core:network tests:</strong> Interceptor behavior, retry logic, token refresh. No feature-specific logic.</p><p><strong>:core:database tests:</strong> Migration tests for every schema version bump. Use MigrationTestHelper.</p><p><strong>:feature:payments tests:</strong> Transfer ViewModel, payment validation, API error handling. Uses fakes for :core:network interfaces.</p><p><strong>:feature:accounts tests:</strong> Balance sync, statement loading, account filtering. Completely independent of payments tests.</p><h3>The key rule</h3><p>Feature module tests should never depend on another feature module. If :feature:payments tests need account data, they use a FakeAccountRepository that implements the interface from :core:common. This mirrors the production architecture and keeps test execution fast.</p><h3>What We Don’t Test (And Why)</h3><p><strong>Not every line of code needs a test. Testing everything dilutes the signal.</strong> Here’s what we intentionally skip:</p><p><strong>Compose UI layout tests.</strong> We don’t test that a button is 48dp tall or that text is the right color. These change frequently and visual regression tools catch them better.</p><p><strong>Simple data classes.</strong> If a class has no logic, it doesn’t need a test. data class Account(val id: String, val balance: Double) is self-verifying.</p><p><strong>Framework behavior.</strong> We don’t test that Room actually persists data or that Retrofit actually makes HTTP calls. Those are the framework’s tests, not ours.</p><p><strong>One-liner mappers.</strong> fun toEntity() = Entity(id, name) doesn&#39;t need its own test. If the mapping is wrong, the integration test catches it.</p><p>The time saved by skipping these goes into testing the ViewModel state transitions and error handling where real bugs live.</p><h3>Conclusion</h3><p>Testing strategy matters more than test count. A codebase with 200 focused tests on ViewModel error handling and API failure modes catches more production bugs than one with 2,000 tests that verify button labels.</p><p><strong>Key takeaways:</strong></p><ul><li>80% of production bugs come from ViewModel state, API errors, and navigation edge cases</li><li>Test state transitions, not just happy paths</li><li>Use real (in-memory) Room databases, not mocks</li><li>Every API endpoint needs 5 failure mode tests</li><li>Feature module tests run independently in under 30 seconds</li><li>Skip layout tests, data class tests, and framework behavior tests</li></ul><p>Start with your most-used screen. Write tests for its ViewModel error handling. That single effort will prevent more crashes than 50 UI tests combined.</p><p><strong>Tags</strong>: Android, Kotlin, Testing, Mobile Development, Software Engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e9c398578b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Process Death: The Silent Bug Crash Most Apps Don’t Handle]]></title>
            <link>https://pankajjangid.medium.com/android-process-death-the-silent-bug-crash-most-apps-dont-handle-61c9d06e8dff?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/61c9d06e8dff</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 02:42:26 GMT</pubDate>
            <atom:updated>2026-03-14T02:42:26.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-GcqSk0Zn6oOyVqiYi6rw.png" /></figure><p><em>Your app crashes for background users, and your crash reporting tool never tells you</em></p><p><strong>TL;DR:</strong> Android kills your app’s process when it’s in the background to free memory. When the user returns, the system recreates your Activity but your ViewModel, singletons, and in-memory state are gone. SavedStateHandle is the fix. Here’s how to reproduce, detect, and handle it properly.</p><h3>Introduction</h3><p><strong>About 1 in 3 background app returns involve a process death on low-memory devices.</strong> If your app doesn’t handle this, users see blank screens, crashes, or lost data, and you’ll never find it in Crashlytics because the process was killed cleanly by the system.</p><p>I’ve seen this bug in production on UOB TMRW, where users switch between banking and messaging apps constantly. On devices with 3–4 GB RAM across Southeast Asia, process death isn’t an edge case. It’s a daily occurrence.</p><p>This article covers what process death actually is, how to reproduce it reliably, and the patterns that protect your app. If you’ve ever had a user report “the app lost my form data” or “I came back and it was on a weird screen,” process death is likely the cause.</p><h3>What Is Process Death</h3><p><strong>The Android OS kills your app’s process when it needs memory for other apps, and it does this without calling onDestroy().</strong> Your app just stops existing. No callback, no warning, no crash report.</p><p>Here’s what the system does:</p><p>The system keeps your app’s task stack in memory even after killing the process. When the user returns via the recents screen, Android recreates your Activity from scratch. It calls onCreate() with a non-null savedInstanceState Bundle. The system expects your app to restore itself from that Bundle.</p><p>The Linux OOM killer (Low Memory Killer Daemon on Android) assigns priority scores to processes. Foreground apps get the lowest score (least likely to be killed). Background apps with no visible Activity get the highest score. When memory pressure rises, the system kills high-score processes first.</p><p>What Survives vs What Dies</p><h3>What survives</h3><ul><li>The Activity’s savedInstanceState Bundle (up to ~1MB)</li><li>Intent extras passed to the Activity</li><li>Navigation back stack (if using Jetpack Navigation)</li><li>Pending WorkManager jobs</li><li>SharedPreferences, Room database, and DataStore data (persisted to disk)</li><li>Pending alarms and scheduled notifications</li></ul><h3>What dies</h3><ul><li>All ViewModel instances (ViewModelStore is destroyed with the process)</li><li>Singleton objects and companion object state</li><li>Retrofit/OkHttp instances and cached responses</li><li>Any in-memory data not saved to disk or Bundle</li><li>Coroutine scopes and running jobs</li><li>Dagger/Hilt component instances and their scoped dependencies</li></ul><p>This is the key difference from a configuration change. During rotation, ViewModel survives via NonConfigurationInstances. During process death, the entire process is gone. Every object in your app’s heap is deallocated.</p><h3>How to Reproduce Process Death</h3><p><strong>You can reliably trigger process death in 10 seconds using ADB, and you should test this before every release.</strong> Most developers never test this because they don’t know how.</p><h3>The reliable method</h3><p>Open your app and navigate to the screen you want to test. Press the Home button (don’t press Back). Then run this command:</p><pre>adb shell am kill com.your.package.name<br><br></pre><p>Now switch back to your app from the recents screen. Your Activity will be recreated with savedInstanceState, but all in-memory state is gone.</p><h3>What NOT to do</h3><p>Don’t swipe your app away from recents. That calls onDestroy() and clears the task stack entirely. That&#39;s not process death, that&#39;s the user closing the app.</p><p>Don’t use “Don’t keep activities” in developer options. That destroys Activities on every navigation, which is more aggressive than real process death and tests a different scenario.</p><h3>Automated testing</h3><p>You can write an instrumented test that simulates process death:</p><pre>@Test<br>fun testProcessDeathRecovery() {<br>    // Launch the activity with some state<br>    val scenario = launchActivity&lt;MainActivity&gt;()<br><br>    scenario.onActivity { activity -&gt;<br>        // Set up some state in the ViewModel<br>        activity.viewModel.setUserInput(&quot;test data&quot;)<br>    }<br><br>    // Simulate process death<br>    scenario.recreate()<br><br>    // Verify state is restored<br>    scenario.onActivity { activity -&gt;<br>        assertEquals(&quot;test data&quot;, activity.viewModel.getUserInput())<br>    }<br>}<br><br></pre><p>The scenario.recreate() call destroys and recreates the Activity with the saved Bundle, simulating what happens after process death.</p><h3>The Wrong Way: ViewModel Alone</h3><p><strong>If you store state only in ViewModel without SavedStateHandle, that state disappears on process death.</strong> This is the most common mistake in Android apps today.</p><p>Here’s the pattern that breaks:</p><pre>// This ViewModel loses ALL state on process death<br>class CheckoutViewModel : ViewModel() {<br>    private val _selectedItems = MutableStateFlow&lt;List&lt;Item&gt;&gt;(emptyList())<br>    val selectedItems: StateFlow&lt;List&lt;Item&gt;&gt; = _selectedItems<br><br>    private val _promoCode = MutableStateFlow(&quot;&quot;)<br>    val promoCode: StateFlow&lt;String&gt; = _promoCode<br><br>    fun setPromoCode(code: String) {<br>        _promoCode.value = code<br>    }<br>}<br><br></pre><p>The user fills in a promo code, switches to a messaging app to copy a code from a friend, and comes back. If the process was killed, _promoCode is back to an empty string. The user&#39;s input is gone.</p><h3>The Right Way: SavedStateHandle</h3><p>SavedStateHandle Flow</p><p><strong>SavedStateHandle is a key-value map that automatically saves to and restores from the Activity’s savedInstanceState Bundle.</strong> It survives both configuration changes and process death.</p><pre>class CheckoutViewModel(<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br><br>    // This survives process death automatically<br>    val promoCode: StateFlow&lt;String&gt; =<br>        savedStateHandle.getStateFlow(&quot;promo_code&quot;, &quot;&quot;)<br><br>    val selectedItemIds: StateFlow&lt;List&lt;String&gt;&gt; =<br>        savedStateHandle.getStateFlow(&quot;selected_ids&quot;, emptyList())<br><br>    fun setPromoCode(code: String) {<br>        savedStateHandle[&quot;promo_code&quot;] = code<br>    }<br><br>    fun selectItem(itemId: String) {<br>        val current = selectedItemIds.value.toMutableList()<br>        current.add(itemId)<br>        savedStateHandle[&quot;selected_ids&quot;] = current<br>    }<br>}<br><br></pre><h3>How SavedStateHandle works internally</h3><p>SavedStateHandle connects to the Activity’s SavedStateRegistry. When the system calls onSaveInstanceState(), SavedStateRegistry collects all registered SavedStateProviders, including your ViewModel&#39;s SavedStateHandle, and writes them into the Bundle.</p><p>On recreation, SavedStateHandleSupport reads the Bundle and reconstructs the SavedStateHandle with your saved values. Your ViewModel&#39;s constructor receives the restored handle with all the data intact.</p><h3>What to save and what not to save</h3><p><strong>Save in SavedStateHandle:</strong> User input, selected IDs, scroll position, navigation arguments, form state, filter selections. Keep values small and serializable.</p><p><strong>Don’t save in SavedStateHandle:</strong> Large objects, Bitmap data, full API responses, file references. The Bundle has a ~1MB limit shared across ALL saved state in the Activity. Save large data to Room or DataStore, and save only the ID or key in SavedStateHandle.</p><h3>Navigation and Process Death</h3><p><strong>Jetpack Navigation automatically saves and restores the back stack, but your destination arguments and ViewModel state still need SavedStateHandle.</strong> The navigation graph survives, but the data each screen holds does not.</p><p>A common failure pattern:</p><pre>// Fragment A passes data to Fragment B via ViewModel sharing<br>// This breaks on process death because the shared ViewModel is gone<br>val sharedViewModel: SharedViewModel by activityViewModels()<br><br></pre><p>The fix is to pass data through Navigation arguments (which are saved in the Bundle) and use SavedStateHandle in each destination’s ViewModel:</p><pre>// Pass data through navigation arguments (survives process death)<br>findNavController().navigate(<br>    R.id.checkoutFragment,<br>    bundleOf(&quot;orderId&quot; to orderId)<br>)<br><br>// Read from SavedStateHandle in the destination ViewModel<br>class CheckoutViewModel(<br>    savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    // Navigation arguments are automatically in SavedStateHandle<br>    val orderId: String = savedStateHandle.get&lt;String&gt;(&quot;orderId&quot;) ?: &quot;&quot;<br>}<br><br></pre><h3>Real-World Impact: What We Found at UOB TMRW</h3><p><strong>When we audited process death handling across 8 feature modules, we found 14 screens that lost state on background return.</strong> The worst offender was the fund transfer screen, where users lost the recipient account number, transfer amount, and selected source account after switching to another app to verify details.</p><p>On low-RAM devices common in Southeast Asia (3–4 GB RAM), process death happened on roughly 25–30% of background returns when users had 5+ apps in recents. That translated to thousands of abandoned transfers per week. After implementing SavedStateHandle across all critical screens, form abandonment dropped by 40%.</p><p>The key insight: process death isn’t theoretical. It directly affects conversion rates, user trust, and support tickets. In fintech, a user losing their transfer form mid-flow doesn’t just cause frustration, it causes calls to customer support.</p><h3>A Practical Process Death Checklist</h3><p><strong>Run this checklist on every screen of your app before release.</strong> It takes 5 minutes per screen and catches bugs that affect millions of users.</p><p><strong>For every screen, ask:</strong></p><ul><li>Does the screen show correct data after adb shell am kill?</li><li>Are user inputs (text fields, selections) preserved?</li><li>Does the loading state not re-trigger unnecessarily?</li><li>Is the scroll position restored?</li><li>Does navigation back work correctly?</li></ul><p><strong>Architecture rules:</strong></p><ul><li>Every ViewModel that holds user-generated state should use SavedStateHandle</li><li>Navigation arguments should carry IDs, not full objects</li><li>Large data belongs in Room/DataStore, referenced by ID in SavedStateHandle</li><li>Test process death in CI with ActivityScenario.recreate()</li></ul><h3>Conclusion</h3><p>Process death is not an edge case. On devices with limited RAM, it happens regularly. The fix is straightforward: use SavedStateHandle for user state, pass IDs through Navigation arguments, and test with adb shell am kill before every release.</p><p><strong>Key takeaways:</strong></p><ul><li>ViewModel alone does NOT survive process death, only config changes</li><li>SavedStateHandle writes to the Activity’s savedInstanceState Bundle automatically</li><li>The Bundle has a ~1MB limit, so save IDs and keys, not full objects</li><li>adb shell am kill is the only reliable way to test this</li><li>Every screen in your app should pass the process death checklist</li></ul><p>The next time a user says “the app lost my data,” you’ll know exactly where to look.</p><p><strong>Tags</strong>: Android, Kotlin, Mobile Development, Android Development, Software Engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61c9d06e8dff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Scaled Android to 3M+ Users with Multi-Module Clean Architecture]]></title>
            <link>https://pankajjangid.medium.com/how-we-scaled-android-to-3m-users-with-multi-module-clean-architecture-94238f486c20?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/94238f486c20</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 00:38:59 GMT</pubDate>
            <atom:updated>2026-03-11T00:38:59.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIoZS4k1Cp47U-dmqSkCDA.png" /></figure><p><em>Real lessons from building UOB TMRW across 4 countries with 8+ feature modules</em></p><p><strong>TL;DR:</strong> We broke a monolithic Android app into 8+ feature modules using Clean Architecture, cutting build times by 40%, reducing merge conflicts by 60%, and enabling 4 teams to ship independently. The result: 3M+ users across Thailand, Singapore, Malaysia, and Indonesia with a 96% crash-free rate.</p><h3>Introduction</h3><p>Our Android codebase hit 200K+ lines and build times crossed 6 minutes. Every pull request touched shared files, and merge conflicts became a daily ritual. Something had to change.</p><p>UOB TMRW is a digital banking app serving 3M+ users across Southeast Asia. When I joined the team, we had a single-module Gradle project where a change in the payments feature could break the accounts screen. Feature teams were stepping on each other’s code constantly.</p><p>This article walks through how we migrated to a multi-module Clean Architecture setup, the real trade-offs we faced, and the measurable results after 12 months in production. If you’re working on an Android app with more than 3 developers or 50K+ lines of code, this is for you.</p><h3>The Challenge</h3><p><strong>Build times were killing productivity.</strong> A full Gradle build took over 6 minutes. Incremental builds often invalidated because shared utility classes changed frequently. Developers context-switched while waiting, and that killed focus.</p><p>The deeper problem was coupling. Our app had a single :app module with packages for each feature, but nothing stopped a developer from importing classes across feature boundaries. The payments module depended on 12 classes from the accounts module. The login flow had references scattered across 5 packages.</p><p>We tried a few things first:</p><p><strong>Package-by-feature convention.</strong> We reorganized packages, but without compile-time enforcement, imports leaked across boundaries within weeks.</p><p><strong>Build cache optimization.</strong> Helped with clean builds, but incremental builds still invalidated because of tight coupling.</p><p><strong>Code reviews for dependency checks.</strong> Manual review doesn’t scale. Reviewers missed cross-feature imports regularly.</p><p>The turning point was a production bug where a change in the transfer module broke biometric authentication. The root cause was a shared utility class that both features modified independently. That incident gave us the mandate to modularize properly.</p><h3>The Strategy</h3><p><strong>We chose a layered module structure with strict dependency rules enforced by Gradle.</strong> This approach gave us compile-time guarantees that no feature module could directly access another feature’s internals.</p><p>Here’s the module structure we settled on:</p><p>Module Dependency Graph</p><pre>:app                    (Application shell, DI wiring)<br>:core:network           (Retrofit setup, interceptors, API models)<br>:core:database          (Room database, DAOs, migrations)<br>:core:common            (Extensions, base classes, shared utilities)<br>:core:ui                (Design system, common composables, themes)<br>:feature:accounts       (Account list, details, statements)<br>:feature:payments       (Fund transfer, bill pay, scheduling)<br>:feature:cards          (Card management, limits, activation)<br>:feature:onboarding     (Registration, KYC, document upload)<br>:feature:settings       (Profile, preferences, security settings)<br>:feature:notifications  (Push handling, notification center)<br>:feature:biometric      (Fingerprint, face ID, device binding)<br>:feature:forex          (Currency exchange, rates, conversion)<br><br></pre><h3>Key architectural decisions</h3><p><strong>Decision 1: Features depend on </strong><strong>:core modules only, never on other features.</strong></p><p>This is the most important rule. If payments needs account data, it goes through a shared interface in :core:common, not by importing from :feature:accounts.</p><pre>// core/common/src/.../AccountRepository.kt<br>interface AccountRepository {<br>    suspend fun getAccounts(): List&lt;Account&gt;<br>    suspend fun getAccountById(id: String): Account?<br>}<br><br></pre><p>The actual implementation lives in :feature:accounts, but the interface is in :core:common. Payments depends on the interface. Dagger provides the implementation at runtime.</p><p><strong>Decision 2: Navigation between features uses a shared route contract.</strong></p><p>Features can’t reference each other’s Activities or Fragments directly. We defined route constants in :core:common:</p><pre>// core/common/src/.../NavRoutes.kt<br>object NavRoutes {<br>    const val ACCOUNTS_DETAIL = &quot;accounts/detail/{accountId}&quot;<br>    const val PAYMENTS_TRANSFER = &quot;payments/transfer/{fromAccountId}&quot;<br>    const val CARDS_ACTIVATE = &quot;cards/activate/{cardId}&quot;<br>}<br><br></pre><p>Each feature module registers its own navigation graph. The :app module wires them together. This means you can swap out an entire feature module without touching any other feature&#39;s code.</p><p><strong>Decision 3: Each feature module owns its own Gradle dependencies.</strong></p><p>No more “add it to the shared build.gradle and every module gets it.” Each feature declares exactly what it needs. This cut unnecessary transitive dependencies and reduced per-module APK contribution.</p><pre>// feature/payments/build.gradle.kts<br>dependencies {<br>    implementation(project(&quot;:core:network&quot;))<br>    implementation(project(&quot;:core:common&quot;))<br>    implementation(project(&quot;:core:ui&quot;))<br>    // Only payments needs this<br>    implementation(libs.mpandroidchart)<br>}<br><br></pre><p><strong>Decision 4: Clean Architecture layers inside each feature module.</strong></p><p>Every feature module follows the same internal structure:</p><pre>feature/payments/<br>  data/          (Repository implementations, API calls, mappers)<br>  domain/        (Use cases, domain models, repository interfaces)<br>  presentation/  (ViewModels, UI state, Compose screens)<br><br></pre><p>This keeps each feature self-contained. A new developer can understand the payments feature by reading one module, without context from the rest of the app.</p><h3>The Implementation</h3><p><strong>A team of 4 Android developers executed the migration over 3 months, running old and new modules in parallel.</strong> We didn’t do a big-bang rewrite. Instead, we extracted one feature at a time while keeping the app releasable.</p><p>Migration Timeline</p><h3>Week 1–2: Core foundation</h3><p>Created :core:network and :core:common modules. Moved shared interfaces, base classes, and network setup. This was the foundation everything else depended on.</p><h3>Week 3–4: First feature extraction</h3><p>Extracted :feature:settings first. Settings had the fewest dependencies on other features, making it the safest starting point.</p><h3>Week 5–8: The hard ones</h3><p>Extracted :feature:accounts and :feature:payments. These were the most coupled modules. We identified 23 cross-feature imports that needed interface extraction.</p><h3>Week 9–12: Everything else</h3><p>Extracted remaining features. By this point, the pattern was clear and each extraction took 3–5 days.</p><h3>The critical moment</h3><p>Week 6 almost derailed us. The payments module had a circular dependency with accounts. Payments needed account balances for validation, and accounts needed payment history for the statement screen.</p><p>The fix was extracting shared domain models into :core:common:</p><pre>// core/common/src/.../models/TransactionSummary.kt<br>data class TransactionSummary(<br>    val accountId: String,<br>    val totalDebits: BigDecimal,<br>    val totalCredits: BigDecimal,<br>    val lastTransactionDate: LocalDate<br>)<br><br></pre><p>Both modules consumed this model through their own repository interfaces. No circular dependency. The lesson: if two features share a concept, that concept belongs in :core.</p><h3>Build configuration that enforces boundaries</h3><p>We added a Gradle convention plugin that fails the build if a feature module tries to depend on another feature:</p><pre>// build-logic/src/.../FeatureModulePlugin.kt<br>class FeatureModulePlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        target.afterEvaluate {<br>            configurations.all {<br>                dependencies.forEach { dep -&gt;<br>                    if (dep is ProjectDependency &amp;&amp;<br>                        dep.dependencyProject.path.startsWith(&quot;:feature:&quot;) &amp;&amp;<br>                        dep.dependencyProject.path != target.path) {<br>                        throw GradleException(<br>                            &quot;Feature module ${target.path} cannot depend on ${dep.dependencyProject.path}&quot;<br>                        )<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br></pre><p>This catches violations at compile time, not during code review.</p><h3>The Results</h3><p>Before vs After Results</p><p><strong>Incremental builds dropped from 90 seconds to 25 seconds, a 72% reduction.</strong> That single metric changed how our team worked. After 12 months in production with the modular architecture, here are the full numbers:</p><p><strong>Full build time:</strong> 6+ minutes → 3.5 minutes (-40%)</p><p><strong>Incremental build:</strong> 90 seconds → 25 seconds (-72%)</p><p><strong>Merge conflicts/week:</strong> ~15 → ~6 (-60%)</p><p><strong>Feature delivery time:</strong> 3 weeks avg → 2 weeks avg (-35%)</p><p><strong>Crash-free rate:</strong> 93.2% → 96%+ (+3%)</p><p><strong>APK size:</strong> 28 MB → 21 MB (-25%)</p><p>The incremental build improvement was the biggest win for developer experience. When you change a file in :feature:payments, only that module rebuilds. The other 7 feature modules stay cached.</p><h3>Results we didn’t expect</h3><p><strong>Onboarding time dropped significantly.</strong> New developers could understand one feature module in isolation. They didn’t need to build a mental model of the entire app before making their first commit. A new team member shipped their first feature PR within the first week.</p><p><strong>Testing became modular too.</strong> Each feature module has its own test suite. You can run :feature:payments:test in 8 seconds instead of running the full app test suite in 4 minutes. Teams started writing more tests because the feedback loop was fast.</p><h3>Key Takeaways</h3><p><strong>Five lessons that saved us from re-learning the same mistakes on future projects.</strong> Each one came from a real incident during the migration, not from a textbook.</p><p><strong>Start with core modules before extracting features.</strong> Shared interfaces, network layer, and design system need to exist before features can be isolated. Skipping this creates circular dependencies.</p><p><strong>Extract the least-coupled feature first.</strong> Settings or profile screens usually have minimal dependencies. Use that extraction to establish the pattern, then tackle complex features.</p><p><strong>Enforce boundaries with Gradle, not code reviews.</strong> Convention plugins that fail the build on cross-feature dependencies are worth the setup time. Manual enforcement doesn’t scale past 3 developers.</p><p><strong>Shared concepts belong in core:common, not in either feature.</strong> If two features need the same domain model, extract it. The cost of a small shared module is lower than the cost of a circular dependency.</p><p><strong>Measure before and after.</strong> Build time, merge conflicts, crash rates, delivery cadence. Without metrics, you can’t prove the investment was worth it, and for a 3-month migration, you need proof.</p><h3>Conclusion</h3><p>Multi-module Clean Architecture isn’t just about code organization. It’s about enabling teams to work independently at scale. The upfront cost is real: 3 months of migration work for our team. But the payoff compounds. Faster builds, fewer conflicts, safer releases, and developers who can own their feature end-to-end.</p><p>If your team has more than 3 Android developers or your build times are over 2 minutes, start planning the migration. Begin with :core:network, extract your simplest feature, and enforce the boundaries from day one.</p><p><strong>Tags</strong>: Android, Clean Architecture, Kotlin, Mobile Development, Software Architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94238f486c20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose State Management: What Android Developers Get Wrong]]></title>
            <link>https://pankajjangid.medium.com/jetpack-compose-state-management-what-android-developers-get-wrong-ca3a22c2a2a9?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca3a22c2a2a9</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 09:17:54 GMT</pubDate>
            <atom:updated>2026-03-08T09:17:54.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vebmTqq34TgTryXrMmyww.png" /></figure><p><em>The mental model shift that separates buggy UIs from rock-solid ones</em></p><p>Most Compose state bugs come from treating state like XML Views, not from Compose itself. The three patterns that cause 90% of issues: holding state in composables instead of ViewModels, triggering recomposition storms with unstable types, and misusing remember across configuration changes. Fix these, and your Compose UI gets predictable.</p><p>I have been shipping Compose in production for over two years now. Across 8+ feature modules in a fintech app serving 3M+ users, I have watched the same state management mistakes repeat themselves in code reviews. Not edge cases. Fundamental misunderstandings about how Compose thinks about state.</p><p>This article breaks down the patterns I see most often, why they happen, and how to fix them with real code.</p><h3>Why State Management in Compose Feels Different</h3><p>Compose recomposes your UI whenever state changes, and this happens far more often than most developers expect. In a typical screen with a form, scroll position, and network data, recomposition can fire dozens of times per second during user interaction. The framework is designed for this. Your code might not be.</p><p>The root problem is mental model mismatch. With XML Views, you mutated widgets directly: textView.text = &quot;Hello&quot;. State lived everywhere, and the framework did not care. Compose flips this entirely. State flows downward, events flow upward, and the framework re-executes your composable functions whenever their inputs change.</p><p>If you carry the old mental model into Compose, you will write code that fights the framework. And the framework always wins.</p><h3>Mistake 1: Holding State Inside Composables</h3><p>About 60% of the state bugs I see in code reviews trace back to one pattern: putting mutableStateOf directly inside a composable without thinking about where that state actually lives.</p><p>Here is the code that looks fine but breaks on rotation:</p><pre>// BAD: State lives inside the composable<br>@Composable<br>fun LoginScreen() {<br>    var email by remember { mutableStateOf(&quot;&quot;) }<br>    var password by remember { mutableStateOf(&quot;&quot;) }<br>    var isLoading by remember { mutableStateOf(false) }<br><br>    // User types email, rotates phone... email is gone<br>    Column {<br>        TextField(value = email, onValueChange = { email = it })<br>        TextField(value = password, onValueChange = { password = it })<br>        Button(onClick = { isLoading = true }) {<br>            if (isLoading) CircularProgressIndicator()<br>            else Text(&quot;Login&quot;)<br>        }<br>    }<br>}<br><br></pre><p>The remember function survives recomposition, but it does not survive configuration changes. Rotate the device, and every field resets. The loading state vanishes. Your user just lost their typed password.</p><h3>The Fix: Hoist State to a ViewModel</h3><pre>// GOOD: State lives in ViewModel, survives config changes<br>class LoginViewModel : ViewModel() {<br>    var email by mutableStateOf(&quot;&quot;)<br>        private set<br>    var password by mutableStateOf(&quot;&quot;)<br>        private set<br>    var isLoading by mutableStateOf(false)<br>        private set<br><br>    fun updateEmail(value: String) { email = value }<br>    fun updatePassword(value: String) { password = value }<br><br>    fun login() {<br>        isLoading = true<br>        viewModelScope.launch {<br>            // network call<br>            isLoading = false<br>        }<br>    }<br>}<br><br>@Composable<br>fun LoginScreen(viewModel: LoginViewModel = viewModel()) {<br>    Column {<br>        TextField(<br>            value = viewModel.email,<br>            onValueChange = viewModel::updateEmail<br>        )<br>        TextField(<br>            value = viewModel.password,<br>            onValueChange = viewModel::updatePassword<br>        )<br>        Button(onClick = viewModel::login) {<br>            if (viewModel.isLoading) CircularProgressIndicator()<br>            else Text(&quot;Login&quot;)<br>        }<br>    }<br>}<br><br></pre><p>The ViewModel survives configuration changes through the ViewModelStore attached to the Activity’s lifecycle. The composable becomes a pure rendering function: it reads state, it sends events up, it does not own anything.</p><h3>When `remember` Is Actually Fine</h3><p>Not every piece of state needs a ViewModel. Ephemeral UI state that has no business logic belongs in the composable:</p><pre>// FINE: Scroll position is ephemeral UI state<br>@Composable<br>fun ItemList(items: List&lt;Item&gt;) {<br>    val listState = rememberLazyListState()<br>    LazyColumn(state = listState) {<br>        items(items) { item -&gt; ItemRow(item) }<br>    }<br>}<br><br></pre><p>The rule is simple. If losing the state on rotation would confuse the user, hoist it to a ViewModel. If the user would not notice, remember is fine.</p><h3>Mistake 2: Recomposition Storms from Unstable Types</h3><p>Compose skips recomposition of a composable when its inputs have not changed. But “changed” depends on how Compose compares parameters. When you pass unstable types, Compose cannot prove they are the same, so it recomposes every single time.</p><p>This matters for performance. I profiled a list screen in our production app that was recomposing 47 times per scroll gesture. The culprit was a data class containing a List parameter. Compose treats List as unstable because it is an interface, and someone could pass a MutableList that changes between reads.</p><pre>// UNSTABLE: Compose recomposes this on every parent recomposition<br>data class UserProfile(<br>    val name: String,<br>    val tags: List&lt;String&gt;  // List is unstable<br>)<br><br>@Composable<br>fun ProfileCard(profile: UserProfile) {<br>    // This recomposes even when profile hasn&#39;t changed<br>    Column {<br>        Text(profile.name)<br>        profile.tags.forEach { Text(it) }<br>    }<br>}<br><br></pre><h3>The Fix: Use Immutable Collections or @Stable</h3><pre>// STABLE: Use kotlinx.collections.immutable<br>import kotlinx.collections.immutable.ImmutableList<br>import kotlinx.collections.immutable.toImmutableList<br><br>data class UserProfile(<br>    val name: String,<br>    val tags: ImmutableList&lt;String&gt;  // Compose knows this won&#39;t change<br>)<br><br>// Or annotate the class<br>@Stable<br>data class UserProfile(<br>    val name: String,<br>    val tags: List&lt;String&gt;<br>) {<br>    // By marking @Stable, you promise Compose:<br>    // 1. equals() will always return the same result for same inputs<br>    // 2. When a public property changes, Composition is notified<br>    // 3. All public properties are stable<br>}<br><br></pre><p>After switching to ImmutableList in our production app, recompositions on that list screen dropped from 47 to 3 per scroll gesture. That is a 94% reduction just from fixing the type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP6yKIS4HdwSOfR_Lg6Bow.png" /></figure><h3>How to Detect Recomposition Issues</h3><p>Use the Compose compiler metrics to find unstable classes in your codebase:</p><pre>// build.gradle.kts<br>kotlinOptions {<br>    freeCompilerArgs += listOf(<br>        &quot;-P&quot;, &quot;plugin:androidx.compose.compiler.plugins.kotlin:&quot; +<br>              &quot;reportsDestination=${buildDir}/compose_metrics&quot;<br>    )<br>}<br><br></pre><p>Check the generated *-classes.txt file. Every class marked unstable is a potential recomposition problem.</p><h3>Mistake 3: Misusing derivedStateOf</h3><p>I see derivedStateOf used as a performance optimization everywhere, including places where it actively makes things worse. The function is not a general-purpose caching tool. It has a specific use case: deriving new state from other state objects when the derivation is expensive or the derived value changes less frequently than its inputs.</p><pre>// BAD: derivedStateOf adds overhead for no benefit<br>@Composable<br>fun Greeting(name: String) {<br>    // name changes every recomposition anyway<br>    val greeting by remember {<br>        derivedStateOf { &quot;Hello, $name!&quot; }<br>    }<br>    Text(greeting)<br>}<br><br></pre><p>The problem here is that name is a plain parameter, not a state object. The derivedStateOf has no way to observe changes to it. It only works with State objects like mutableStateOf or values from StateFlow.collectAsState().</p><h3>When derivedStateOf Actually Helps</h3><pre>// GOOD: Derived state changes less frequently than input<br>@Composable<br>fun ItemListWithHeader(items: List&lt;Item&gt;) {<br>    val listState = rememberLazyListState()<br><br>    // firstVisibleItemIndex changes every pixel of scroll<br>    // but &quot;should show button&quot; only changes at the threshold<br>    val showScrollToTop by remember {<br>        derivedStateOf { listState.firstVisibleItemIndex &gt; 5 }<br>    }<br><br>    Box {<br>        LazyColumn(state = listState) {<br>            items(items) { ItemRow(it) }<br>        }<br>        if (showScrollToTop) {<br>            FloatingActionButton(onClick = { /* scroll to top */ }) {<br>                Icon(Icons.Default.KeyboardArrowUp, &quot;Scroll to top&quot;)<br>            }<br>        }<br>    }<br>}<br><br></pre><p>Here firstVisibleItemIndex changes on every frame during scrolling. But the boolean showScrollToTop only flips when crossing the threshold of 5. Without derivedStateOf, the FAB would recompose on every scroll frame. With it, the FAB only recomposes when visibility actually changes.</p><h3>Mistake 4: Collecting Flows Without Lifecycle Awareness</h3><p>StateFlow and SharedFlow are the standard way to expose state from ViewModels. But how you collect them in Compose determines whether your app wastes battery in the background.</p><pre>// BAD: Collects even when app is in background<br>@Composable<br>fun UserScreen(viewModel: UserViewModel = viewModel()) {<br>    val user by viewModel.userState.collectAsState()<br>    // This keeps collecting when the app is backgrounded<br>}<br><br></pre><h3>The Fix: Use collectAsStateWithLifecycle</h3><pre>// GOOD: Stops collecting when lifecycle drops below STARTED<br>@Composable<br>fun UserScreen(viewModel: UserViewModel = viewModel()) {<br>    val user by viewModel.userState.collectAsStateWithLifecycle()<br>    // Automatically stops collection in onStop, resumes in onStart<br>}<br><br></pre><p>The collectAsStateWithLifecycle() function from androidx.lifecycle:lifecycle-runtime-compose respects the lifecycle. When the user presses Home, collection stops. When they return, it resumes. On a fintech app with real-time data feeds, this single change reduced our background CPU usage by roughly 30%.</p><p>The only time you want collectAsState() without lifecycle awareness is when your flow must keep collecting in the background. That is rare in UI code.</p><h3>Mistake 5: State Holder Classes Without remember</h3><p>For screens with complex state logic, a state holder class keeps your composable clean. But I have seen developers create the state holder without remember, causing a new instance on every recomposition.</p><pre>// BAD: New FormState created on every recomposition<br>@Composable<br>fun RegistrationForm() {<br>    val formState = FormState()  // New instance every recomposition!<br>    // All validation state resets on each recomposition<br>}<br><br>class FormState {<br>    var name by mutableStateOf(&quot;&quot;)<br>    var email by mutableStateOf(&quot;&quot;)<br>    var nameError by mutableStateOf&lt;String?&gt;(null)<br><br>    fun validate(): Boolean {<br>        nameError = if (name.isBlank()) &quot;Required&quot; else null<br>        return nameError == null<br>    }<br>}<br><br></pre><h3>The Fix: rememberSaveable with a Custom Saver</h3><pre>// GOOD: State holder survives recomposition AND config changes<br>@Composable<br>fun rememberFormState(): FormState {<br>    return rememberSaveable(saver = FormState.Saver) {<br>        FormState()<br>    }<br>}<br><br>class FormState {<br>    var name by mutableStateOf(&quot;&quot;)<br>    var email by mutableStateOf(&quot;&quot;)<br>    var nameError by mutableStateOf&lt;String?&gt;(null)<br><br>    fun validate(): Boolean {<br>        nameError = if (name.isBlank()) &quot;Required&quot; else null<br>        return nameError == null<br>    }<br><br>    companion object {<br>        val Saver = mapSaver(<br>            save = { mapOf(&quot;name&quot; to it.name, &quot;email&quot; to it.email) },<br>            restore = { FormState().apply {<br>                name = it[&quot;name&quot;] as String<br>                email = it[&quot;email&quot;] as String<br>            }}<br>        )<br>    }<br>}<br><br>@Composable<br>fun RegistrationForm() {<br>    val formState = rememberFormState()<br>    // Survives recomposition AND rotation<br>}<br><br></pre><p>The rememberSaveable with a custom Saver handles both recomposition and process death. For simpler cases where you do not need process death survival, remember { FormState() } is enough.</p><h3>The State Decision Tree</h3><p>When you are unsure where to put state, walk through these questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbEcYNiPBGPQl_WCTHa7AQ.png" /></figure><ol><li><strong>Is it ephemeral UI state?</strong> (scroll position, animation, hover) Use remember or rememberLazyListState().</li><li><strong>Does it need to survive configuration changes?</strong> (form input, selected tab) Use ViewModel with mutableStateOf or StateFlow.</li><li><strong>Does it need to survive process death?</strong> (draft text, navigation state) Use rememberSaveable or SavedStateHandle in ViewModel.</li><li><strong>Is it shared across screens?</strong> Use a shared ViewModel scoped to the navigation graph, or a repository layer.</li><li><strong>Is it derived from other state?</strong> Use derivedStateOf only when the derived value changes less frequently than its source.</li></ol><h3>Conclusion</h3><p>Compose state management is not complicated once you stop fighting the framework. The mental model shift is the hard part, and it comes down to three principles:</p><ul><li><strong>State flows down, events flow up.</strong> Composables render state, they do not own it. Hoist business state to ViewModels.</li><li><strong>Stability determines performance.</strong> Use immutable types or @Stable annotations. Check your Compose compiler metrics for unstable classes.</li><li><strong>Lifecycle matters for collection.</strong> Always use collectAsStateWithLifecycle() unless you have a specific reason not to.</li><li><strong>Choose the right </strong><strong>remember variant.</strong> Plain remember for recomposition survival, rememberSaveable for config changes and process death.</li><li><strong>Use </strong><strong>derivedStateOf only when the output changes less frequently than the input.</strong> It is not a cache, it is a frequency reducer.</li></ul><p>These patterns have held up across 8 feature modules and 3M+ users in production. They will hold up in your codebase too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca3a22c2a2a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Android Apps for Fintech: Lessons from 3M+ Users]]></title>
            <link>https://pankajjangid.medium.com/securing-android-apps-for-fintech-lessons-from-3m-users-d8ccf71dd969?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ccf71dd969</guid>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 11:54:05 GMT</pubDate>
            <atom:updated>2026-03-04T11:58:46.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ndt9p8MgQuGjUrt-2ALsw.png" /></figure><h3>What I learned building a banking app used across 4 countries</h3><p>If you’re building a fintech app, security isn’t a feature. It’s the foundation. One vulnerability in a banking app doesn’t just crash your app, it drains someone’s account.</p><p>I’ve spent the last few years working on UOB TMRW, a digital banking app serving 3M+ users across Thailand, Singapore, Malaysia, and Indonesia. Every security decision I’m sharing here comes from real production experience, real penetration test findings, and real regulatory requirements across multiple countries.</p><p>This article covers the security patterns that actually matter: authentication, data protection, network security, and the subtle mistakes that slip through code reviews.</p><h3>1. Threat Modeling: Know What You’re Protecting</h3><p>Before writing a single line of security code, map out what attackers want and how they’d get it.</p><p>For a fintech app, the threat model looks like this:</p><ul><li><strong>Credential theft</strong>: Intercepting login tokens or session cookies</li><li><strong>Man-in-the-middle (MITM)</strong>: Sniffing API traffic between app and server</li><li><strong>Reverse engineering</strong>: Decompiling the APK to extract API keys or business logic</li><li><strong>Device compromise</strong>: Rooted devices, screen overlays, accessibility service abuse</li><li><strong>Session hijacking</strong>: Stealing or replaying authentication tokens</li></ul><p>Most teams jump straight to implementation. The ones that build secure apps start by listing what can go wrong.</p><h3>Prioritize by Impact</h3><p>Not all threats deserve equal attention. A stolen session token is worse than a decompiled APK. Focus your effort where the financial damage is highest.</p><p>I use a simple matrix: likelihood (low/medium/high) vs impact (low/medium/high). Anything in the high-impact column gets addressed before launch. Everything else goes into the hardening backlog.</p><h3>2. OAuth 2.0 + PKCE: Authentication Done Right</h3><p>If your fintech app still uses a simple username/password flow with a long-lived token, you’re one intercepted request away from a breach.</p><p><strong>OAuth 2.0 with PKCE</strong> (Proof Key for Code Exchange) is the standard for mobile apps. Here’s why: mobile apps can’t keep secrets. Unlike server-side apps, your client_secret is embedded in a decompilable APK. PKCE eliminates the need for a client secret entirely.</p><h3>The Flow</h3><pre>// 1. Generate a random code_verifier (43-128 chars)<br>fun generateCodeVerifier(): String {<br>    val bytes = ByteArray(32)<br>    SecureRandom().nextBytes(bytes)<br>    return Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)<br>}</pre><pre>// 2. Create code_challenge from verifier<br>fun generateCodeChallenge(verifier: String): String {<br>    val digest = MessageDigest.getInstance(&quot;SHA-256&quot;).digest(verifier.toByteArray())<br>    return Base64.encodeToString(digest, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)<br>}</pre><pre>// 3. Send code_challenge in authorization request<br>// 4. Send code_verifier in token exchange<br>// Server verifies: SHA256(code_verifier) == code_challenge</pre><p>The code_verifier never leaves your app until token exchange. Even if an attacker intercepts the authorization code, they can’t exchange it without the verifier.</p><h3>Token Storage</h3><p>Never store tokens in SharedPreferences (plain text on disk). Use <strong>EncryptedSharedPreferences</strong> from the AndroidX Security library:</p><pre>val masterKey = MasterKey.Builder(context)<br>    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>    .build()</pre><pre>val securePrefs = EncryptedSharedPreferences.create(<br>    context,<br>    &quot;secure_token_prefs&quot;,<br>    masterKey,<br>    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>)</pre><pre>// Store token<br>securePrefs.edit().putString(&quot;access_token&quot;, token).apply()</pre><p>Under the hood, this uses Android Keystore for key management. The encryption key is hardware-backed on devices that support it, meaning even root access doesn’t trivially expose the key material.</p><h3>Token Refresh Strategy</h3><p>Short-lived access tokens (5–15 minutes) with refresh tokens is the pattern. But the refresh token itself needs protection:</p><ul><li>Store refresh tokens in EncryptedSharedPreferences</li><li>Implement refresh token rotation (each refresh gives a new refresh token)</li><li>Detect refresh token reuse as a signal of theft, and invalidate the entire session</li></ul><h3>3. Biometric Authentication: Beyond the Happy Path</h3><p>BiometricPrompt is straightforward to implement. Making it secure is a different story.</p><h3>The Wrong Way</h3><pre>// DON&#39;T: Using biometric as a simple gate<br>biometricPrompt.authenticate(promptInfo)<br>// onAuthenticationSucceeded -&gt; proceed to app<br>// This just checks &quot;is a valid fingerprint on this device?&quot;<br>// An attacker with a rooted device can spoof this callback.</pre><h3>The Right Way: CryptoObject Binding</h3><p>Tie biometric authentication to a cryptographic operation. The biometric unlock should decrypt something meaningful, not just flip a boolean.</p><pre>// Generate a key that requires biometric auth to use<br>val keyGenerator = KeyGenerator.getInstance(<br>    KeyProperties.KEY_ALGORITHM_AES, &quot;AndroidKeyStore&quot;<br>)<br>keyGenerator.init(<br>    KeyGenParameterSpec.Builder(&quot;biometric_key&quot;,<br>        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)<br>        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)<br>        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)<br>        .setUserAuthenticationRequired(true)<br>        .setUserAuthenticationParameters(<br>            0, // every use requires auth<br>            KeyProperties.AUTH_BIOMETRIC_STRONG<br>        )<br>        .build()<br>)<br>keyGenerator.generateKey()</pre><pre>// Create cipher tied to biometric-protected key<br>val cipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;)<br>val key = (KeyStore.getInstance(&quot;AndroidKeyStore&quot;).apply { load(null) })<br>    .getKey(&quot;biometric_key&quot;, null)<br>cipher.init(Cipher.ENCRYPT_MODE, key)</pre><pre>// Authenticate with CryptoObject<br>val cryptoObject = BiometricPrompt.CryptoObject(cipher)<br>biometricPrompt.authenticate(promptInfo, cryptoObject)</pre><p>When onAuthenticationSucceeded fires, the cipher inside CryptoObject is now unlocked by the Trusted Execution Environment (TEE). Use it to encrypt/decrypt the actual session token. If biometric auth is spoofed, the cipher won&#39;t be unlocked, and the token stays encrypted.</p><h3>Edge Cases That Bite</h3><ul><li><strong>Fingerprint changes</strong>: When a user adds a new fingerprint, Android invalidates biometric-protected keys. Handle KeyPermanentlyInvalidatedException gracefully, don&#39;t crash, re-enroll the user.</li><li><strong>Biometric enrollment check</strong>: Always verify BiometricManager.canAuthenticate(BIOMETRIC_STRONG) before showing the prompt. Devices without enrolled biometrics will throw confusing errors.</li><li><strong>Fallback flow</strong>: Some regulators require a PIN/password fallback. Use setAllowedAuthenticators(BIOMETRIC_STRONG or DEVICE_CREDENTIAL) carefully, DEVICE_CREDENTIAL alone doesn&#39;t provide the same security guarantees.</li></ul><h3>4. Certificate Pinning Without Bricking Your App</h3><p>Certificate pinning prevents MITM attacks by rejecting any TLS certificate that doesn’t match your expected server certificate. Essential for fintech. But get it wrong and your app stops working entirely when certificates rotate.</p><h3>Network Security Config (Recommended)</h3><pre>&lt;!-- res/xml/network_security_config.xml --&gt;<br>&lt;network-security-config&gt;<br>    &lt;domain-config&gt;<br>        &lt;domain includeSubdomains=&quot;true&quot;&gt;api.yourbank.com&lt;/domain&gt;<br>        &lt;pin-set expiration=&quot;2027-01-01&quot;&gt;<br>            &lt;!-- Pin the intermediate CA, not the leaf certificate --&gt;<br>            &lt;pin digest=&quot;SHA-256&quot;&gt;base64EncodedSHA256Hash=&lt;/pin&gt;<br>            &lt;!-- ALWAYS include a backup pin --&gt;<br>            &lt;pin digest=&quot;SHA-256&quot;&gt;backupBase64EncodedSHA256Hash=&lt;/pin&gt;<br>        &lt;/pin-set&gt;<br>    &lt;/domain-config&gt;<br>&lt;/network-security-config&gt;</pre><h3>Critical Rules</h3><ol><li><strong>Pin the intermediate CA, not the leaf</strong>: Leaf certificates rotate frequently. Intermediate CAs rotate on a multi-year cycle. Pinning the leaf means your app breaks every time the server renews its certificate.</li><li><strong>Always include a backup pin</strong>: If your primary certificate is compromised or rotates unexpectedly, the backup pin keeps the app alive. Without it, you’re shipping an emergency hotfix.</li><li><strong>Set an expiration date</strong>: The expiration attribute in Network Security Config is your safety net. After expiration, pinning is disabled and any valid certificate works. This prevents permanent app bricking if all your pins become invalid.</li><li><strong>OkHttp CertificatePinner as a fallback</strong>:</li></ol><pre>val certificatePinner = CertificatePinner.Builder()<br>    .add(&quot;api.yourbank.com&quot;, &quot;sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=&quot;)<br>    .add(&quot;api.yourbank.com&quot;, &quot;sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=&quot;)<br>    .build()</pre><pre>val client = OkHttpClient.Builder()<br>    .certificatePinner(certificatePinner)<br>    .build()</pre><p>I prefer Network Security Config because it’s declarative and doesn’t require a code change to update pins. But OkHttp CertificatePinner gives you programmatic control and better error handling.</p><h3>The Rotation Problem</h3><p>The biggest risk with certificate pinning isn’t attackers. It’s your own ops team rotating certificates without telling the mobile team. Build a monitoring system:</p><ul><li>Track pin expiration dates in your CI/CD pipeline</li><li>Alert 90 days before expiration</li><li>Test pin validation in your integration test suite</li><li>Have a remote config kill switch to disable pinning in emergencies</li></ul><h3>5. Encrypted Storage: What Actually Needs Encryption</h3><p>Not everything needs encryption. Encrypt selectively, because encryption has a performance cost.</p><h3>Must Encrypt</h3><ul><li>Authentication tokens (access, refresh, session)</li><li>User PII (name, phone, national ID)</li><li>Financial data (account numbers, transaction history cached locally)</li><li>Biometric enrollment keys</li></ul><h3>Don’t Bother Encrypting</h3><ul><li>App settings (theme, language)</li><li>Non-sensitive cache (images, generic API responses)</li><li>Analytics event queue</li></ul><h3>Room Database Encryption with SQLCipher</h3><p>For structured sensitive data, encrypt your Room database:</p><pre>// build.gradle<br>implementation(&quot;net.zetetic:android-database-sqlcipher:4.5.4&quot;)<br>implementation(&quot;androidx.sqlite:sqlite-ktx:2.4.0&quot;)</pre><pre>// Database setup<br>val passphrase = getOrCreateDatabasePassphrase() // from Android Keystore<br>val factory = SupportFactory(SQLiteDatabase.getBytes(passphrase.toCharArray()))</pre><pre>val database = Room.databaseBuilder(context, AppDatabase::class.java, &quot;secure.db&quot;)<br>    .openHelperFactory(factory)<br>    .build()</pre><p>Store the database passphrase in Android Keystore, not hardcoded. Generate it once on first launch, retrieve it on subsequent launches.</p><h3>EncryptedFile for Sensitive Documents</h3><pre>val masterKey = MasterKey.Builder(context)<br>    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>    .build()</pre><pre>val encryptedFile = EncryptedFile.Builder(<br>    context,<br>    File(context.filesDir, &quot;sensitive_document.pdf&quot;),<br>    masterKey,<br>    EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB<br>).build()</pre><pre>// Write<br>encryptedFile.openFileOutput().use { output -&gt;<br>    output.write(sensitiveData)<br>}</pre><h3>6. Runtime Security Checks</h3><p>A secured app also needs to know when its environment is compromised.</p><h3>Root Detection</h3><p>Rooted devices can bypass most app-level security. You don’t need to block rooted users entirely (some are legitimate developers), but you should adjust behavior:</p><pre>object SecurityEnvironment {</pre><pre>    fun isDeviceCompromised(context: Context): Boolean {<br>        return hasRootIndicators() || isRunningOnEmulator() || hasDebuggerAttached()<br>    }</pre><pre>    private fun hasRootIndicators(): Boolean {<br>        val paths = listOf(<br>            &quot;/system/app/Superuser.apk&quot;,<br>            &quot;/system/xbin/su&quot;,<br>            &quot;/system/bin/su&quot;,<br>            &quot;/sbin/su&quot;<br>        )<br>        return paths.any { File(it).exists() }<br>    }</pre><pre>    private fun isRunningOnEmulator(): Boolean {<br>        return Build.FINGERPRINT.contains(&quot;generic&quot;)<br>            || Build.MODEL.contains(&quot;Emulator&quot;)<br>            || Build.MANUFACTURER.contains(&quot;Genymotion&quot;)<br>    }</pre><pre>    private fun hasDebuggerAttached(): Boolean {<br>        return Debug.isDebuggerConnected() || Debug.waitingForDebugger()<br>    }<br>}</pre><p>For production fintech apps, use Google’s <strong>Play Integrity API</strong> (successor to SafetyNet). It gives you a cryptographically signed verdict about device integrity, app integrity, and licensing status. Much harder to spoof than local checks.</p><h3>Tapjacking Protection</h3><p>Screen overlay attacks (tapjacking) trick users into tapping on something they can’t see. Android has a built-in defense:</p><pre>// In your sensitive Activity (payment screens, OTP entry)<br>window.setFlags(<br>    WindowManager.LayoutParams.FLAG_SECURE,<br>    WindowManager.LayoutParams.FLAG_SECURE<br>)</pre><pre>// For specific views handling sensitive input<br>sensitiveButton.filterTouchesWhenObscured = true</pre><p>FLAG_SECURE also prevents screenshots and screen recording, which is a regulatory requirement for most banking apps.</p><h3>7. ProGuard/R8: Your First Line of Defense Against Reverse Engineering</h3><p>Code obfuscation won’t stop a determined attacker. But it raises the cost of reverse engineering significantly.</p><pre># Keep security-critical class names for debugging<br>-keep class com.yourapp.security.** { *; }</pre><pre># Obfuscate everything else aggressively<br>-optimizationpasses 5<br>-allowaccessmodification<br>-repackageclasses &#39;&#39;</pre><pre># Remove logging in release builds<br>-assumenosideeffects class android.util.Log {<br>    public static int d(...);<br>    public static int v(...);<br>    public static int i(...);<br>}</pre><p>The Log removal rule is critical. I&#39;ve seen banking apps ship with debug logs that print authentication tokens to Logcat. R8 strips these calls entirely from release builds.</p><h3>Beyond R8</h3><p>For fintech apps handling high-value transactions, consider:</p><ul><li><strong>String encryption</strong>: Tools like DexGuard or manual encryption for sensitive strings (API endpoints, key names)</li><li><strong>Integrity checks</strong>: Verify your APK signature at runtime to detect repackaging</li><li><strong>Native code</strong>: Move critical crypto operations to native (C/C++) code via JNI, harder to decompile than Dalvik bytecode</li></ul><h3>Security Testing Checklist</h3><p>Before every release, run through this:</p><ul><li>All API traffic uses TLS 1.2+ with certificate pinning active</li><li>Tokens stored in EncryptedSharedPreferences, never plain SharedPreferences</li><li>Biometric auth uses CryptoObject binding, not just callback gating</li><li>No sensitive data in Logcat (test with adb logcat on release build)</li><li>FLAG_SECURE on all screens showing financial data</li><li>ProGuard/R8 rules verified, no sensitive classes exposed</li><li>Root detection active with graceful degradation</li><li>Backup pin configured for certificate pinning</li><li>Play Integrity API integrated and verdicts enforced</li><li>Penetration test report clear (run at least annually)</li></ul><h3>Conclusion</h3><p>Security in fintech isn’t about adding one library or following one pattern. It’s a layered defense where each layer compensates for the weaknesses of others.</p><p>Here’s what I’d prioritize if you’re starting from scratch:</p><ol><li><strong>OAuth 2.0 + PKCE</strong> for authentication, never roll your own token scheme</li><li><strong>EncryptedSharedPreferences</strong> for all sensitive local storage</li><li><strong>Certificate pinning</strong> with backup pins and expiration dates</li><li><strong>CryptoObject-bound biometrics</strong>, not simple callback gating</li><li><strong>Play Integrity API</strong> for runtime environment validation</li><li><strong>R8 with log stripping</strong> as the bare minimum obfuscation</li></ol><p>Every pattern in this article comes from production incidents, penetration test findings, or regulatory audits across 4 countries. Security is not a one-time implementation. It’s an ongoing practice.</p><p>Build it right from the start. Your users are trusting you with their money.</p><p><strong>Tags</strong>: Android, Kotlin, Mobile Security, Fintech, Mobile Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ccf71dd969" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StateFlow vs SharedFlow: What Every Android Developer Gets Wrong]]></title>
            <link>https://pankajjangid.medium.com/stateflow-vs-sharedflow-what-every-android-developer-gets-wrong-47e0519bd5f7?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e0519bd5f7</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 08:34:37 GMT</pubDate>
            <atom:updated>2026-03-03T08:51:03.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XEBe-yxfSyHSmaaQvk0ZQ.png" /></figure><p><em>You’re probably using StateFlow where SharedFlow belongs, or worse, forcing</em></p><p><em>SharedFlow to act like StateFlow. Here’s how to pick the right one.</em></p><p>Most Android developers treat StateFlow and SharedFlow as interchangeable. I&#39;ve seen this in code reviews, in interviews, and honestly, in my own code a few years back. Both emit values, both are hot flows, both live inside kotlinx.coroutines. So what&#39;s the difference?</p><p>The difference isn’t just about API signatures. It’s about <strong>what kind of data you’re modeling</strong>. StateFlow models <em>state</em>. SharedFlow models <em>events</em>. Confuse the two and you’ll end up with lost UI events, duplicate navigation calls, or stale data that refuses to update.</p><p>This article breaks down the internals of both, shows where each one shines, and walks through the real-world mistakes I’ve seen in production apps serving millions of users.</p><h3>The Core Mental Model</h3><p>Before touching any code, get this mental model right:</p><ul><li><strong>StateFlow</strong> = a variable that notifies observers when it changes. Think of it as a reactive var. It always holds a value, and new collectors immediately get the latest one.</li><li><strong>SharedFlow</strong> = a broadcast channel for events. Think of it as a reactive event bus. It doesn’t hold a “current” value by default, and events can be lost if nobody is listening.</li></ul><p>This distinction drives every behavioral difference between the two.</p><h3>StateFlow: Under the Hood</h3><p>StateFlow is actually a specialized SharedFlow with specific configuration baked in. If you look at the Kotlin source, MutableStateFlow internally uses:</p><ul><li>A <strong>replay cache of 1</strong> (new collectors always get the latest value)</li><li><strong>distinctUntilChanged</strong> behavior (only emits when the value actually changes)</li><li>A <strong>conflated buffer</strong> (if the collector is slow, intermediate values are dropped, only the latest survives)</li></ul><pre>// Creating a StateFlow<br>private val _uiState = MutableStateFlow(HomeScreenState())<br>val uiState: StateFlow&lt;HomeScreenState&gt; = _uiState.asStateFlow()</pre><pre>// Updating state<br>fun loadData() {<br>    viewModelScope.launch {<br>        _uiState.value = _uiState.value.copy(isLoading = true)<br>        val result = repository.fetchItems()<br>        _uiState.value = _uiState.value.copy(<br>            isLoading = false,<br>            items = result<br>        )<br>    }<br>}</pre><h3>Why distinctUntilChanged Matters</h3><p>StateFlow uses <strong>structural equality</strong> (equals()) to decide whether a new value is actually &quot;new.&quot; If you emit the same object, collectors won&#39;t be notified.</p><p>This trips people up with data classes:</p><pre>// This WON&#39;T trigger a re-emission<br>_uiState.value = _uiState.value.copy() // same values, same object via equals()</pre><pre>// This WILL trigger a re-emission<br>_uiState.value = _uiState.value.copy(timestamp = System.currentTimeMillis())</pre><p>If your state object doesn’t implement equals() properly (or you&#39;re using a regular class instead of a data class), you&#39;ll get unexpected behavior. StateFlow will compare references, and every .copy() creates a new reference, so it will always emit.</p><h3>The Conflation Problem</h3><p>Because StateFlow is conflated, intermediate states get dropped if the collector can’t keep up. In most UI scenarios this is exactly what you want. Your screen only cares about the latest state, not every intermediate loading/success/error transition.</p><p>But if you need every state change to be processed (like logging each state transition), StateFlow is the wrong tool.SharedFlow: Under the Hood</p><p>SharedFlow is the more flexible primitive. You configure its behavior through three parameters:</p><pre>MutableSharedFlow&lt;T&gt;(<br>    replay: Int = 0,           // how many past emissions new collectors receive<br>    extraBufferCapacity: Int = 0,  // buffer beyond replay cache<br>    onBufferOverflow: BufferOverflow = SUSPEND  // what happens when buffer is full<br>)</pre><h3>Replay Cache</h3><p>The replay parameter controls how many past emissions a new collector receives when it starts collecting. This is the key differentiator:</p><ul><li>replay = 0: New collectors get nothing from the past. They only see future emissions. This is what you want for one-time events like navigation commands or snackbar messages.</li><li>replay = 1: Behaves similarly to StateFlow (new collectors get the last emitted value), but without distinctUntilChanged and without requiring an initial value.</li><li>replay = N: New collectors get the last N emissions. Useful for chat message history or log buffers.</li></ul><h3>No Initial Value Required</h3><p>Unlike StateFlow, SharedFlow doesn’t need an initial value. This matters when your “initial state” is genuinely unknown:</p><pre>// StateFlow forces you to provide an initial value<br>private val _user = MutableStateFlow&lt;User?&gt;(null) // awkward null initial</pre><pre>// SharedFlow doesn&#39;t<br>private val _user = MutableSharedFlow&lt;User&gt;(replay = 1) // no emission until data exists</pre><h3>Buffer Overflow Strategies</h3><p>When the buffer is full and a new value arrives, you have three options:</p><pre>// SUSPEND: The emitter suspends until there&#39;s room (default)<br>MutableSharedFlow&lt;Event&gt;(extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.SUSPEND)</pre><pre>// DROP_OLDEST: Drop the oldest value in the buffer<br>MutableSharedFlow&lt;Event&gt;(extraBufferCapacity = 10, onBufferOverflow = BufferOverflow.DROP_OLDEST)</pre><pre>// DROP_LATEST: Drop the new value being emitted<br>MutableSharedFlow&lt;Event&gt;(extraBufferCapacity = 10, onBufferOverflow = BufferOverflow.DROP_LATEST)</pre><p>In ViewModels, I typically use DROP_OLDEST for UI events. You don&#39;t want the coroutine to suspend (blocking further processing) just because the UI hasn&#39;t consumed an old event yet.The Real Difference: State vs Events</p><p>This is where most developers go wrong. They use StateFlow for everything because it’s simpler. But state and events have fundamentally different requirements:</p><h3>State (Use StateFlow)</h3><ul><li>Has a <strong>current value</strong> at all times</li><li>New observers need the <strong>latest value</strong> immediately</li><li>Duplicate consecutive values are <strong>irrelevant</strong></li><li>Examples: UI state, user profile, loading status, form data</li></ul><h3>Events (Use SharedFlow)</h3><ul><li>Are <strong>transient</strong>, they happen and they’re done</li><li>Should be processed <strong>exactly once</strong></li><li>Duplicate consecutive values <strong>matter</strong> (two identical error messages are two events)</li><li>Examples: navigation commands, snackbar messages, click events, error toasts</li></ul><p>Here’s the classic mistake:</p><pre>// WRONG: Using StateFlow for one-time events<br>private val _navigateToDetail = MutableStateFlow&lt;String?&gt;(null)</pre><pre>fun onItemClicked(id: String) {<br>    _navigateToDetail.value = id<br>}</pre><pre>// Problem: After navigation, the value is still &quot;id&quot;.<br>// On configuration change, the collector picks up the stale value<br>// and navigates AGAIN.</pre><p>The “fix” people try is resetting the value to null after consuming:</p><pre>// Still fragile<br>fun onNavigationHandled() {<br>    _navigateToDetail.value = null<br>}</pre><p>This works until you have multiple collectors, or until the timing is off. The correct approach:</p><pre>// RIGHT: SharedFlow for one-time events<br>private val _navigateToDetail = MutableSharedFlow&lt;String&gt;()</pre><pre>fun onItemClicked(id: String) {<br>    viewModelScope.launch {<br>        _navigateToDetail.emit(id)<br>    }<br>}</pre><p>With replay = 0, the event fires once and is gone. No stale state, no reset needed.Collecting Safely in Android</p><p>Both StateFlow and SharedFlow are hot flows. They emit regardless of whether anyone is collecting. In Android, you need to collect them lifecycle-aware to avoid processing events when the UI is in the background.</p><h3>The Modern Way: repeatOnLifecycle</h3><pre>// In your Fragment or Activity<br>lifecycleScope.launch {<br>    repeatOnLifecycle(Lifecycle.State.STARTED) {<br>        // This block runs when STARTED, cancels when STOPPED</pre><pre>        // Collect state<br>        launch {<br>            viewModel.uiState.collect { state -&gt;<br>                renderState(state)<br>            }<br>        }</pre><pre>        // Collect events<br>        launch {<br>            viewModel.events.collect { event -&gt;<br>                handleEvent(event)<br>            }<br>        }<br>    }<br>}</pre><h3>The Compose Way</h3><pre>@Composable<br>fun HomeScreen(viewModel: HomeViewModel) {<br>    // StateFlow -&gt; collectAsStateWithLifecycle<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()</pre><pre>    // SharedFlow -&gt; LaunchedEffect<br>    LaunchedEffect(Unit) {<br>        viewModel.events.collect { event -&gt;<br>            when (event) {<br>                is NavigateToDetail -&gt; navController.navigate(event.route)<br>                is ShowSnackbar -&gt; snackbarHostState.showSnackbar(event.message)<br>            }<br>        }<br>    }</pre><pre>    // Render UI based on uiState<br>    HomeContent(uiState)<br>}</pre><p>Notice the pattern: collectAsStateWithLifecycle() for StateFlow (because you want the latest state for recomposition), and LaunchedEffect with manual collect for SharedFlow events.</p><h3>Event Loss: The SharedFlow Gotcha</h3><p>With replay = 0, if nobody is collecting when an event is emitted, <strong>that event is lost</strong>. This happens in practice when:</p><ol><li>The UI is in the background (collector was cancelled by repeatOnLifecycle)</li><li>The ViewModel emits a navigation event from a background operation</li><li>User brings the app back, the event is gone</li></ol><p>Two ways to handle this:</p><h3>Option 1: Buffer the events</h3><pre>private val _events = MutableSharedFlow&lt;UiEvent&gt;(<br>    extraBufferCapacity = 1,<br>    onBufferOverflow = BufferOverflow.DROP_OLDEST<br>)</pre><p>This holds one event even if nobody is collecting. When the collector resumes, it picks up the buffered event. Not perfect for multiple rapid events, but works for most cases.</p><h3>Option 2: Use a Channel</h3><p>For strict exactly-once delivery, Channel is actually the right tool:</p><pre>private val _events = Channel&lt;UiEvent&gt;(Channel.BUFFERED)<br>val events = _events.receiveAsFlow()</pre><pre>fun onItemClicked(id: String) {<br>    viewModelScope.launch {<br>        _events.send(NavigateToDetail(id))<br>    }<br>}</pre><p>A Channel buffers events and delivers them to exactly one collector. Events survive collector restarts and are never duplicated. I use this pattern in banking apps where event loss is not acceptable.Common Interview Questions</p><p>If you’re preparing for Android interviews, here are the questions I ask (and what I expect in a strong answer):</p><p><strong>Q: What’s the difference between StateFlow and SharedFlow?</strong></p><p>A weak answer lists API differences. A strong answer explains the state vs event mental model, mentions distinctUntilChanged and conflation in StateFlow, and brings up replay cache configuration in SharedFlow.</p><p><strong>Q: How do you handle one-time events in a ViewModel?</strong></p><p>A weak answer says “use LiveData Event wrapper.” A strong answer discusses SharedFlow with replay = 0 or Channel, explains why StateFlow is wrong for events, and mentions the event loss problem with background collectors.</p><p><strong>Q: Why not just use LiveData for everything?</strong></p><p>StateFlow and SharedFlow are coroutine-native, work outside of Android (in shared KMP modules), support backpressure configuration, and don’t require the main thread for observation. LiveData still works fine, but Flow-based solutions are where the ecosystem is heading.</p><h3>Key Takeaways</h3><ul><li><strong>StateFlow</strong> = reactive state holder. Always has a value, conflated, uses distinctUntilChanged. Use for UI state.</li><li><strong>SharedFlow</strong> = reactive event broadcaster. Configurable replay and buffer. Use for one-time events.</li><li>StateFlow is actually a specialized SharedFlow with replay=1, distinctUntilChanged, and conflation.</li><li>For strict one-time event delivery, consider Channel over SharedFlow.</li><li>Always collect lifecycle-aware: repeatOnLifecycle in Views, collectAsStateWithLifecycle in Compose.</li><li>The right choice depends on your data model: is it state (current value matters) or an event (occurrence matters)?</li></ul><p>Pick the right tool for the right job. Your future self debugging a double-navigation bug at 2 AM will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e0519bd5f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Android ViewModel: How Does It Work Under the Hood?]]></title>
            <link>https://pankajjangid.medium.com/demystifying-android-viewmodel-how-does-it-work-under-the-hood-7756e23f0855?source=rss-3c9992fed030------2</link>
            <guid isPermaLink="false">https://medium.com/p/7756e23f0855</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[mobile-appdevelopment]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <dc:creator><![CDATA[Pankaj Jangid]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 09:22:38 GMT</pubDate>
            <atom:updated>2024-09-01T09:22:38.955Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ever wondered what magic keeps your app’s data intact during configuration changes? Let’s dive deep into Android’s ViewModel and unravel its internal workings!</em></p><h3>Introduction</h3><p>Imagine you’re using a navigation app while driving, and you rotate your phone to get a better view. You wouldn’t want the app to restart or lose your current route, right? Similarly, in app development, ensuring data persists across configuration changes like screen rotations is crucial for seamless user experience. This is where Android’s <strong>ViewModel</strong> comes into play.</p><p>In this article, we’ll explore the inner workings of Android ViewModel, understand how it manages to retain data across configuration changes, and learn how it contributes to building robust and efficient applications. We’ll break down complex concepts into relatable explanations and practical examples, making it easy for you to grasp and implement in your projects.</p><h3>What is a ViewModel?</h3><p>At its core, a <strong>ViewModel</strong> is a class designed to store and manage UI-related data in a lifecycle-conscious way. It allows data to survive configuration changes such as screen rotations, ensuring a smooth and consistent user experience.</p><p><strong>Analogy Time:</strong> Think of ViewModel as a <strong>dedicated assistant</strong> for your activity or fragment. This assistant keeps track of important information, so even if your activity needs to restart (like when the screen rotates), your assistant still holds all the necessary data ready to be used again.</p><p><strong>Key Responsibilities of ViewModel:</strong></p><ul><li><strong>Data Persistence:</strong> Maintains UI-related data during configuration changes.</li><li><strong>Lifecycle Awareness:</strong> Knows about the lifecycle of its associated UI controllers (activities/fragments) and acts accordingly.</li><li><strong>Separation of Concerns:</strong> Helps in keeping the UI controllers lean by handling data operations, leading to cleaner and more maintainable code.</li></ul><h3>The Need for ViewModel</h3><p>Before ViewModel was introduced, developers faced challenges in maintaining data consistency during configuration changes. Traditional methods involved using onSaveInstanceState() or retaining fragments, which could be cumbersome and error-prone.</p><p><strong>Problems with Old Approaches:</strong></p><ul><li><strong>Complexity:</strong> Manually handling data saving and restoration increased code complexity.</li><li><strong>Performance Issues:</strong> Large amounts of data could cause performance bottlenecks when saved in onSaveInstanceState().</li><li><strong>Error-Prone:</strong> Increased chances of bugs due to manual handling of lifecycle events.</li></ul><p><strong>Enter ViewModel:</strong> ViewModel addresses these issues by providing a simple and effective way to retain data seamlessly, reducing boilerplate code and potential errors.</p><h3>How ViewModel Works Internally</h3><p>Understanding the internal mechanics of ViewModel helps in leveraging its full potential. Let’s dissect how ViewModel operates under the hood.</p><h3>Lifecycle Awareness</h3><p>ViewModel is designed to be <strong>lifecycle-aware</strong>, meaning it knows about the lifecycle states of its associated UI controllers and behaves accordingly.</p><ul><li><strong>Creation:</strong> A ViewModel is created when the UI controller (activity/fragment) requests it for the first time.</li><li><strong>Retention:</strong> It is retained as long as the UI controller is alive and during its configuration changes.</li><li><strong>Destruction:</strong> It is cleared when the UI controller is finished or destroyed permanently.</li></ul><p><strong>How Does It Achieve This?</strong> ViewModel leverages <strong>Android Architecture Components</strong> to monitor lifecycle events and manage its existence appropriately.</p><h3>ViewModelStore and ViewModelProvider</h3><p>Two key players facilitate the lifecycle management of ViewModel: <strong>ViewModelStore</strong> and <strong>ViewModelProvider</strong>.</p><h4>ViewModelStore</h4><ul><li><strong>Role:</strong> Acts as a container that holds ViewModel instances.</li><li><strong>Functionality:</strong> Ensures that ViewModels are retained across configuration changes by storing them in a place that’s not affected by such changes.</li></ul><p><strong>Analogy:</strong> Think of ViewModelStore as a <strong>secure locker</strong> that keeps your important documents (ViewModels) safe, regardless of what’s happening outside (configuration changes).</p><h4>ViewModelProvider</h4><ul><li><strong>Role:</strong> Responsible for creating and retrieving ViewModel instances from the ViewModelStore.</li><li><strong>Functionality:</strong> Provides a way to obtain ViewModels scoped to the lifecycle of UI controllers.</li></ul><p><strong>Process Flow:</strong></p><ol><li>When a ViewModel is requested, ViewModelProvider checks the ViewModelStore.</li><li>If the ViewModel exists, it returns the existing instance.</li><li>If not, it creates a new instance and stores it in the ViewModelStore for future use.</li></ol><p><strong>Code Illustration:</strong></p><pre>class MainActivity : AppCompatActivity() {<br>    private lateinit var viewModel: MainViewModel<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        // Obtaining ViewModel instance<br>        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)<br>        setContentView(R.layout.activity_main)<br>    }<br>}<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        // Obtaining ViewModel instance<br>        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)<br>        setContentView(R.layout.activity_main)<br>    }<br>}</pre><p>In this example, ViewModelProvider checks if MainViewModel exists in the ViewModelStore. If it does, it provides the existing instance; otherwise, it creates and stores a new one.</p><h3>Data Retention Across Configuration Changes</h3><p>The magic of data retention lies in the separation between the <strong>UI controllers</strong> and the <strong>ViewModelStore</strong>.</p><ul><li><strong>Configuration Change Occurs:</strong> When a configuration change happens (e.g., screen rotation), the activity is destroyed and recreated.</li><li><strong>ViewModel Retention:</strong> Since ViewModelStore is associated with the activity’s lifecycle owner but exists outside the activity itself, it survives the destruction and recreation process.</li><li><strong>Data Persistence:</strong> The new instance of the activity retrieves the same ViewModel from the ViewModelStore, maintaining continuity in data.</li></ul><p><strong>Visual Representation:</strong></p><pre>[Activity Instance 1] --requests--&gt; [ViewModel] stored in [ViewModelStore]<br>      | (configuration change)<br>[Activity Instance 2] --requests--&gt; [Same ViewModel] from [ViewModelStore]</pre><p><strong>Benefits:</strong></p><ul><li><strong>Seamless Data Persistence:</strong> Users experience no data loss during configuration changes.</li><li><strong>Efficient Resource Usage:</strong> Prevents unnecessary data re-fetching or recomputation.</li><li><strong>Simplified Codebase:</strong> Reduces boilerplate code for handling configuration changes manually.</li></ul><h3>ViewModel in Action: A Practical Example</h3><p>Let’s consider a practical scenario where ViewModel showcases its capabilities.</p><p><strong>Scenario:</strong> Building a news app that fetches and displays articles from an API.</p><p><strong>Without ViewModel:</strong></p><ul><li>On screen rotation, the activity is recreated, and the app re-fetches data from the API.</li><li>This leads to unnecessary network calls and a poor user experience due to repeated loading.</li></ul><p><strong>With ViewModel:</strong></p><ol><li><strong>Data Fetching:</strong> The ViewModel fetches data from the API and holds it.</li><li><strong>UI Update:</strong> The activity observes the data from the ViewModel and updates the UI.</li><li><strong>Configuration Change:</strong> On rotation, the activity is recreated but retrieves the same ViewModel instance.</li><li><strong>Data Persistence:</strong> The UI instantly displays the existing data without re-fetching from the API.</li></ol><p><strong>Implementation Example:</strong></p><pre>class NewsViewModel : ViewModel() {<br>    private val _articles = MutableLiveData&lt;List&lt;Article&gt;&gt;()<br>    val articles: LiveData&lt;List&lt;Article&gt;&gt; get() = _articles<br><br>init {<br>        fetchArticles()<br>    }<br>    private fun fetchArticles() {<br>        // Assume we have a Repository that fetches articles<br>        Repository.getArticles { fetchedArticles -&gt;<br>            _articles.postValue(fetchedArticles)<br>        }<br>    }<br>}<br>class NewsActivity : AppCompatActivity() {<br>    private val viewModel: NewsViewModel by viewModels()<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_news)<br>        viewModel.articles.observe(this, { articles -&gt;<br>            // Update UI with articles<br>        })<br>    }<br>}</pre><p><strong>Outcome:</strong></p><ul><li>Users enjoy a smooth experience without redundant loading.</li><li>The app efficiently uses resources by avoiding unnecessary network requests.</li><li>Code remains clean and maintainable by separating concerns effectively.</li></ul><h3>Best Practices for Using ViewModel</h3><p>To harness the full power of ViewModel, consider the following best practices:</p><ol><li><strong>Keep UI Logic Separate:</strong> Use ViewModel strictly for UI-related data and logic; avoid referencing views or context directly to prevent memory leaks.</li><li><strong>Leverage LiveData:</strong> Combine ViewModel with LiveData for observable and lifecycle-aware data handling.</li><li><strong>Avoid Heavy Operations:</strong> Perform intensive tasks like network calls or database operations in repositories or use cases, and supply results to ViewModel.</li><li><strong>Use Factory for Parameters:</strong> When ViewModel requires parameters, utilize ViewModelProvider.Factory to supply dependencies properly.</li></ol><p><strong>Example of ViewModel with Factory:</strong></p><pre>class UserViewModel(private val userId: String) : ViewModel() {<br>    // ViewModel implementation<br>}<br><br>class UserViewModelFactory(private val userId: String) : ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {<br>        return UserViewModel(userId) as T<br>    }<br>}<br>// Usage in Activity<br>val factory = UserViewModelFactory(&quot;user123&quot;)<br>val viewModel = ViewModelProvider(this, factory).get(UserViewModel::class.java)</pre><h3>Conclusion</h3><p>Android’s ViewModel is a powerful tool that simplifies data management across configuration changes, enhances user experience, and promotes clean architecture in app development. By understanding its internal workings and following best practices, developers can build robust, efficient, and user-friendly applications with ease.</p><p>Remember, ViewModel is your app’s trusty assistant, diligently preserving and managing data behind the scenes, so you can focus on delivering exceptional user experiences.</p><h3>Further Reading</h3><ol><li><strong>Android Developers Guide — ViewModel</strong></li></ol><ul><li><a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel Overview</a></li></ul><p>2.<strong> Understanding the ViewModel Lifecycle</strong></p><ul><li><a href="https://medium.com/androiddevelopers/viewmodels-a-simple-example-ed5ac416317e">Lifecycle of ViewModel Explained</a></li></ul><p>3. <strong>Advanced ViewModel Usage</strong></p><ul><li><a href="https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate">ViewModel with SavedState</a></li></ul><p>4. <strong>LiveData and ViewModel</strong></p><ul><li><a href="https://developer.android.com/topic/libraries/architecture/livedata">Working with LiveData</a></li></ul><p>5. <strong>Clean Architecture in Android</strong></p><ul><li><a href="https://proandroiddev.com/clean-architecture-data-flow-dependency-rule-615ffdd79e29">Guide to Clean Architecture</a></li></ul><p>#AndroidDevelopment #ViewModel #MobileAppDevelopment #CleanArchitecture #AndroidJetpack</p><p><em>Thank you for reading! Have any thoughts or questions? Feel free to share them in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7756e23f0855" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>