<?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 Taufik Amaryansyah on Medium]]></title>
        <description><![CDATA[Stories by Taufik Amaryansyah on Medium]]></description>
        <link>https://medium.com/@taufik-amary?source=rss-5cb5152083c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UAFrZmKS8mXLz6LByR28pg.jpeg</url>
            <title>Stories by Taufik Amaryansyah on Medium</title>
            <link>https://medium.com/@taufik-amary?source=rss-5cb5152083c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:46:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taufik-amary/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[Moving Local Storage to Jetpack DataStore Without Paying a Cent in Performance]]></title>
            <link>https://proandroiddev.com/moving-local-storage-to-jetpack-datastore-without-paying-a-cent-in-performance-e709b28719de?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e709b28719de</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-performance]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 10:51:02 GMT</pubDate>
            <atom:updated>2026-10-10T17:14:47.886Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>How we replaced the storage foundation of a large-scale app, then proved it with numbers.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gc7uc3zYCq6vXLB4VMSSrw.jpeg" /><figcaption>Illustration Generated by Gemini</figcaption></figure><h3>TL;DR</h3><ul><li>The most important local data in our app now lives in <strong>Jetpack DataStore</strong>, replacing SharedPreferences.</li><li>We measured the impact with an isolated benchmark: <strong>no measurable runtime cost</strong>. Cold start, hot start, CPU, and memory all stay within normal run-to-run variation.</li><li>Migrating existing users’ data to DataStore runs once and finishes in <strong>tens of milliseconds</strong>, on a background thread.</li><li>In the same release, the app as a whole shows its first screen <strong>0.7 seconds faster</strong> than the previous release on a Samsung Galaxy A55. DataStore did not stand in the way of that.</li></ul><h3>Why we left SharedPreferences</h3><p>SharedPreferences has been part of Android since API 1. It is simple and good enough for many cases. But in an app as large as ours, its limits started to show.</p><p><strong>1. The API is synchronous, and it is often called from the main thread.</strong><br>The first read of a SharedPreferences file blocks the calling thread until the whole file is loaded from disk. If that thread is the main thread, the UI waits too.</p><p><strong>2. </strong><strong>apply() is not fully asynchronous.</strong><br>apply() looks like a background write. But Android waits for every pending apply() to finish when an Activity stops or a Service finishes. On a device with slow storage, that wait can turn into an ANR. commit() is worse, because it blocks explicitly.</p><p><strong>3. Write failures are invisible.</strong><br>apply() never tells you whether the data was actually saved. If it fails, the app never finds out.</p><p><strong>4. There is no convenient reactive way to observe changes.</strong><br>All you get is a listener, which leaks easily and does not fit with coroutines or Flow.</p><p><strong>5. Types are not enforced.</strong><br>Storing an Int and reading it back as a Long only surfaces at runtime, as a ClassCastException.</p><p>Jetpack DataStore was designed to address all of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpJf0xHJNsiuFS7eHG4K5w.png" /><figcaption>SharedPreferences vs Jetpack DataStore</figcaption></figure><h3>Benchmark results</h3><p>The question we heard most before the release: <em>“If the storage moves to DataStore, won’t the app get slower?”</em></p><p>We answered it with several measurements.</p><h4>1. Isolated benchmark: what does DataStore cost on its own?</h4><p>Our release contained many changes besides DataStore. To keep DataStore’s effect from getting mixed in, we built three APKs:</p><ul><li><strong>The previous release.</strong></li><li><strong>The new release without DataStore</strong>, meaning every change in the release except the migration.</li><li><strong>The new release with DataStore</strong>, meaning the build we actually shipped.</li></ul><p>The difference between the second and third builds is the cost of DataStore and nothing else. All three were measured <strong>back to back in a single 24-minute session</strong> on a Xiaomi Redmi Note 9 Pro (Snapdragon 720G, 6 GB RAM), 10 cold starts per build, with normal thermal status on all 30 runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veVbMz3yUODQsrW1qEpL5w.png" /><figcaption>Isolated benchmark results</figcaption></figure><p><strong>DataStore adds no measurable runtime cost.</strong> Every startup, CPU, and memory difference is smaller than the run-to-run variation within the same build. Screens A and B are the two screens users open most. The only consistent change actually goes the right way: CPU on screen B at idle dropped 2.6 points, and that drop showed up in two separate measurement sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02SiOYpbjAz0tCweBZmn6Q.png" /><figcaption>Median cold start of the three builds</figcaption></figure><h4>2. Updating from an old version on a low-end device</h4><p>The hardest scenario for the migration is an existing user updating on an inexpensive device, because that is where the data migration actually runs. We measured it with Perfetto on a <strong>Samsung Galaxy A15</strong>, 10 iterations per build, with old data already in place before the update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MH2EEz4m0AmojlsTA5N8gw.png" /><figcaption>Update on a low-end device</figcaption></figure><p><strong>All 10 cold start iterations and all 10 warm start iterations were faster on the new APK.</strong> That includes the first iteration, the only launch that runs the data migration: 7.04 seconds, no slower than the average.</p><p>The two APKs differ by more than the storage layer, so this speed-up belongs to the release as a whole. What this measurement proves is the thing we worried about most beforehand: <strong>the data migration does not make existing users wait longer</strong>.</p><h4>3. How long does the migration itself take?</h4><p>We record the migration’s duration through telemetry. On our test device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kshfZd4U8xGlci7N_1jUpA.png" /><figcaption>Migration duration</figcaption></figure><p>The migration runs on a background thread and finishes in milliseconds, so users never feel a wait.</p><h4>4. The release as a whole</h4><p>On a <strong>Samsung Galaxy A55</strong>, 10 runs per metric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAo1umXHOFsETzkNs3YWcw.png" /><figcaption>Release overview</figcaption></figure><p>Even the slowest run of the new release was faster than the fastest run of the previous one. This is the work of the whole team on that release, not DataStore alone. But it answers the original concern quite firmly: replacing the storage foundation did not stop the app from getting faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_CYzGPTKtvA6v_GP0jF2Q.png" /><figcaption>Cold start per run</figcaption></figure><h3>What these numbers taught us</h3><p><strong>Measure the change on its own.</strong> Our first measurement compared the old release with the new one and found a CPU increase on one of the screens. Once we built a version without DataStore, it turned out the increase came from other changes in the same release, and DataStore actually brought it down. Without that comparison build, we would have blamed the wrong component.</p><p><strong>Measure in one session.</strong> Measurements taken hours or days apart produced differences that did not hold up when repeated. Network conditions, server-driven content, and device temperature all change in between. Measuring every build back to back in one session removes most of that noise.</p><p><strong>Report the range, not just the average.</strong> Memory on the same screen, for the same build, can move by more than 30 MB between samples. A 14 MB difference in the average between two builds means nothing against variation that large.</p><p><strong>Build in telemetry from the start.</strong> Migration duration and write failures are sent as events. The question “how long does the migration take on users’ devices?” can be answered from production data instead of guesswork.</p><h3>Closing</h3><p>A storage migration is rarely visible to users, and that is exactly how it should be. Its success is measured by what <em>doesn’t</em> happen: no lost data, no interrupted user sessions, no app that got slower.</p><p>These numbers give us the confidence to keep going: moving more data to DataStore does not have to be traded against performance.</p><p>Thank you to everyone involved: those who reviewed the plan again and again, those who tested the update scenarios one by one, and those who ran the benchmarks until the numbers could be trusted.</p><p><em>All numbers in this article come from internal measurements on physical devices. Results on other devices may differ, especially in absolute values.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e709b28719de" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/moving-local-storage-to-jetpack-datastore-without-paying-a-cent-in-performance-e709b28719de">Moving Local Storage to Jetpack DataStore Without Paying a Cent in Performance</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Fighting Your Navigation Library: A Practical Guide to Jetpack Navigation 3]]></title>
            <link>https://proandroiddev.com/stop-fighting-your-navigation-library-a-practical-guide-to-jetpack-navigation-3-dd34c70d6300?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd34c70d6300</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 06:22:01 GMT</pubDate>
            <atom:updated>2026-07-13T03:18:45.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXvJrPhdQ7cMT_LLfa7mbg.png" /><figcaption>Illustration Generated by Gemini</figcaption></figure><p>Navigation has always been one of the trickiest parts of Android development. If you’ve worked with Jetpack Compose, you probably used NavHost and NavController from the original Navigation Compose library. It worked — but let&#39;s be honest, it had its quirks.</p><p>Now, Google has released <strong>Navigation 3</strong> (sometimes called “Nav3”), a completely reimagined navigation library built from the ground up for Jetpack Compose. It’s simpler, truly composable, and gives you full control over your back stack without feeling like a black box.</p><p>In this article, I’ll walk you through Navigation 3 step by step using a real travel destination app called <strong>MyCompose</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bHKd88md7WVf-CcP1xghw.png" /></figure><p>By the end of this read, you’ll understand the core concepts and be ready to migrate or build your next project with Nav3.</p><blockquote><strong><em>Full source code</em></strong><em>: </em><a href="https://github.com/amary21/MyCompose"><em>github.com/amary21/MyCompose</em></a></blockquote><h3>Why Navigation 3? What Changed from Navigation 2?</h3><p>Before we dive into code, let’s understand <strong>why</strong> Google created a new navigation library.</p><h4>The Problems with Navigation 2</h4><ul><li><strong>NavController was a black box</strong> — it managed the back stack internally, making it hard to inspect or manipulate directly as a state.</li><li><strong>It fought Compose’s model</strong> — Navigation 2 was originally designed for XML-based apps. Even though it recently introduced type-safety (in version 2.8.0) to finally replace fragile string routes, the core engine was still the old, rigid NavController rather than a pure Compose state.</li></ul><h4>What Navigation 3 Brings</h4><ul><li><strong>You own the back stack</strong> — it’s just a SnapshotStateList you can read, add to, or remove from.</li><li><strong>Type-safe routes natively</strong> — While you <em>can</em> still use simple strings, the back stack natively supports any object, including Kotlin classes/objects annotated with @Serializable. Say goodbye to fragile string parsing just to extract arguments (like &quot;detail/{id}&quot;).</li><li><strong>Fully composable</strong> — it works <em>with</em> Compose’s mental model instead of against it.</li><li><strong>Simpler API surface</strong> — just 3 core concepts.</li></ul><p>Think of it this way: Navigation 2 was like using a GPS that only let you type a destination. Navigation 3 is like having a map where you can see every stop and rearrange them freely.</p><h3>Setting Up Your Project</h3><h4>Step 1: Add Dependencies</h4><p>In your gradle/libs.versions.toml, add the Navigation 3 version:</p><pre>[versions]<br>nav3Core = &quot;1.1.2&quot;<br>kotlinxSerializationCore = &quot;1.11.0&quot;<br><br>[libraries]<br>androidx-navigation3-runtime = { group = &quot;androidx.navigation3&quot;, name = &quot;navigation3-runtime&quot;, version.ref = &quot;nav3Core&quot; }<br>androidx-navigation3-ui = { group = &quot;androidx.navigation3&quot;, name = &quot;navigation3-ui&quot;, version.ref = &quot;nav3Core&quot; }<br>kotlinx-serialization-core = { group = &quot;org.jetbrains.kotlinx&quot;, name = &quot;kotlinx-serialization-core&quot;, version.ref = &quot;kotlinxSerializationCore&quot; }</pre><h4>Step 2: Apply Plugins</h4><p>In your app/build.gradle.kts:</p><pre>plugins {<br>    alias(libs.plugins.android.application)<br>    alias(libs.plugins.kotlin.compose)<br>    alias(libs.plugins.kotlin.serialization) // Required for type-safe routes<br>}<br><br>dependencies {<br>    implementation(libs.androidx.navigation3.runtime)<br>    implementation(libs.androidx.navigation3.ui)<br>    implementation(libs.kotlinx.serialization.core)<br>}</pre><p>The kotlin.serialization plugin is essential because Navigation 3 uses Kotlin Serialization to serialize and deserialize your route keys.</p><h3>Understanding the Core Concepts</h3><p>Navigation 3 strips away the complexity and leaves you with just <strong>three building blocks</strong>. I like to call this the <strong>Nav3 Core Trinity</strong>:</p><p>💡 <strong>The Nav3 Core Trinity:</strong></p><ul><li><strong>NavKey (The Destination):</strong> <em>Where</em> you want to go. It&#39;s pure data representing a screen.</li><li><strong>NavBackStack (The Journey):</strong> Your travel history. It&#39;s just a reactive list of your keys.</li><li><strong>NavDisplay (The Window):</strong> The UI renderer that observes the top of your stack and shows the right screen.</li></ul><p>Let’s break them down:</p><h4>1. NavKey — Your Route Definition</h4><p>A NavKey is a Kotlin class or object that represents a screen in your app. Think of it as a &quot;ticket&quot; that says where you want to go.</p><pre>import androidx.navigation3.runtime.NavKey<br>import kotlinx.serialization.Serializable<br><br>// A route with no arguments (singleton)<br>@Serializable<br>data object ListRoute : NavKey<br><br>// A route with arguments<br>@Serializable<br>data class DetailRoute(val itemId: Int) : NavKey<br><br>// Another route with no arguments<br>@Serializable<br>data object AboutRoute : NavKey</pre><p><strong>Key points:</strong></p><ul><li>Every route must implement NavKey.</li><li>Every route must be annotated with @Serializable.</li><li>Use data object for screens without arguments.</li><li>Use data class for screens that need arguments (like an item ID).</li></ul><p>This is a <strong>huge improvement</strong> over Navigation 2. No more error-prone strings like navController.navigate(&quot;detail/42&quot;). Now, it&#39;s fully type-safe: backStack.add(DetailRoute(itemId = 42)).</p><h4>2. NavBackStack — Your Navigation State</h4><p>The back stack is simply a list of NavKey items. You can add to it, remove from it, or inspect it — just like any Kotlin list.</p><pre>val backStack = rememberNavBackStack(ListRoute) // Start at ListRoute</pre><ul><li>backStack.add(SomeRoute) → Navigate forward</li><li>backStack.removeLastOrNull() → Go back</li><li>The initial value (ListRoute here) is your start destination</li></ul><p><strong>What about Process Death?</strong></p><p>You might be wondering, <em>“If it’s just a state list, will I lose my back stack on configuration changes or process death?”</em> The answer is no. Under the hood, rememberNavBackStack is built to safely save and restore your navigation state automatically, provided your NavKey classes are properly annotated with @Serializable.</p><h4>3. NavDisplay — Your Screen Renderer</h4><p>NavDisplay reads the top of the back stack and renders the matching screen. It&#39;s like a &quot;screen switcher&quot; that automatically shows the right composable.</p><pre>NavDisplay(<br>    backStack = backStack,<br>    onBack = { backStack.removeLastOrNull() },<br>    entryProvider = entryProvider {<br>        // Define which key maps to which screen<br>    }<br>)</pre><h3>Building the App Step by Step</h3><p>Now let’s see how these concepts come together in a real app. Our sample app — <strong>MyCompose</strong> — is a travel destination explorer with three screens:</p><ul><li><strong>List Screen</strong> — shows a searchable list of Indonesian travel destinations.</li><li><strong>Detail Screen</strong> — shows full details of a selected destination.</li><li><strong>About Screen</strong> — shows developer profile info.</li></ul><h4>The Architecture at a Glance</h4><pre>MainActivity<br> └── AppNavHost()<br>      └── NavDisplay<br>            ├── ListRoute   → ListScreen<br>            ├── DetailRoute → DetailScreen<br>            └── AboutRoute  → AboutScreen</pre><h4>Step 1: Define Your Routes</h4><p>Each screen gets its own route definition. I recommend putting the route class in a separate file alongside the screen it belongs to.</p><p><strong>ListRoute.kt</strong> (No arguments needed):</p><p>Kotlin</p><pre>@Serializable<br>data object ListRoute : NavKey</pre><p><strong>DetailRoute.kt</strong> (Needs an item ID):</p><pre>@Serializable<br>data class DetailRoute(val itemId: Int) : NavKey</pre><p><strong>AboutRoute.kt</strong> (No arguments needed):</p><pre>@Serializable<br>data object AboutRoute : NavKey</pre><h4>Step 2: Create the Navigation Host</h4><p>The AppNavHost is where everything connects. This is the &quot;brain&quot; of your navigation:</p><pre>@Composable<br>fun AppNavHost() {<br>    val backStack = rememberNavBackStack(ListRoute) // 1️⃣ Start here<br>    NavDisplay(<br>        backStack = backStack,                      // 2️⃣ Watch this stack<br>        onBack = { backStack.removeLastOrNull() },  // 3️⃣ Handle back press<br>        entryProvider = entryProvider {             // 4️⃣ Map keys → screens<br>            listRoute(backStack)<br>            detailRoute(backStack)<br>            aboutRoute(backStack)<br>        }<br>    )<br>}</pre><h4>Step 3: Wire Up Each Route</h4><p>This is where Navigation 3 really shines. Each route handler is a clean extension function that connects a NavKey to a @Composable screen.</p><p><strong>List Route (Home Screen)</strong></p><pre>fun EntryProviderScope&lt;NavKey&gt;.listRoute(backStack: NavBackStack&lt;NavKey&gt;) {<br>    entry&lt;ListRoute&gt; {<br>        val viewModel: ListViewModel = viewModel()<br>        val destinations by viewModel.destinations.collectAsStateWithLifecycle()<br>        val query by viewModel.searchQuery.collectAsStateWithLifecycle()<br><br>        ListScreen(<br>            destinations,<br>            query,<br>            onItemClick = { itemId -&gt;<br>                backStack.add(DetailRoute(itemId = itemId))  // Navigate to detail<br>            },<br>            onProfileClick = dropUnlessResumed {<br>                backStack.add(AboutRoute)                    // Navigate to about<br>            },<br>            onAddDestination = viewModel::addDestination,<br>            onSearchQueryChange = viewModel::onSearchQueryChange,<br>            onDeleteDestination = viewModel::deleteDestination<br>        )<br>    }<br>}</pre><p><strong>What’s happening here:</strong></p><ul><li>entry&lt;ListRoute&gt; tells Navigation 3: &quot;When ListRoute is on top of the back stack, run this composable.&quot;</li><li>Inside, we create a ViewModel, collect state, and render ListScreen.</li><li>Navigation is simple: backStack.add(DetailRoute(itemId = itemId)) pushes the detail screen onto the stack.</li></ul><p><strong>Detail Route (With Arguments)</strong></p><pre>fun EntryProviderScope&lt;NavKey&gt;.detailRoute(backStack: NavBackStack&lt;NavKey&gt;) {<br>    entry&lt;DetailRoute&gt; { key -&gt;<br>        val viewModel: DetailViewModel = viewModel()<br>        val destination by viewModel.destination.collectAsStateWithLifecycle()<br><br>        LaunchedEffect(key.itemId) {<br>            viewModel.loadDestination(key.itemId)<br>        }<br><br>        if (destination != null) {<br>            DetailScreen(<br>                destination = destination,<br>                onBack = dropUnlessResumed {<br>                    backStack.removeLastOrNull()<br>                }<br>            )<br>        } else {<br>            NotFoundScreen()<br>        }<br>    }<br>}</pre><p><strong>Key insight:</strong> Notice the key parameter in entry&lt;DetailRoute&gt; { key -&gt; ... }. This is your DetailRoute instance, so you can access key.itemId directly — no string parsing, no SavedStateHandle. Just clean Kotlin.</p><p>Also notice the graceful error handling: if the ID doesn’t match any destination, we show a NotFoundScreen instead of crashing.</p><p><strong>About Route (Simple Screen)</strong></p><pre>fun EntryProviderScope&lt;NavKey&gt;.aboutRoute(backStack: NavBackStack&lt;NavKey&gt;) {<br>    entry&lt;AboutRoute&gt; {<br>        AboutScreen(<br>            onBack = dropUnlessResumed {<br>                backStack.removeLastOrNull()<br>            }<br>        )<br>    }<br>}</pre><h4>Step 4: Plug It Into Your Activity</h4><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            MyComposeTheme {<br>                AppNavHost()  // That&#39;s it!<br>            }<br>        }<br>    }<br>}</pre><h3>Important Pattern: dropUnlessResumed</h3><p>You might have noticed dropUnlessResumed wrapping some click handlers. Here&#39;s why it matters:</p><pre>onProfileClick = dropUnlessResumed {<br>    backStack.add(AboutRoute)<br>}</pre><p><strong>The problem it solves:</strong> When a user taps a button, the navigation happens instantly. But what if they tap <em>really fast</em> and the click fires twice before the first navigation completes? You’d end up with duplicate screens on the back stack!</p><p><strong>dropUnlessResumed</strong> prevents this by ignoring clicks that happen when the current screen is no longer in the &quot;resumed&quot; state. Think of it as a debounce for navigation — it ensures only the first tap counts.</p><p><strong>When to use it:</strong></p><ul><li>✅ Navigation callbacks (going to another screen, going back).</li><li>❌ Data operations (search, delete, add) — these should always work regardless of screen state.</li></ul><h3>The Screen Layer: Keeping UI Pure</h3><p>One best practice demonstrated in this project is the <strong>separation between routes and screens</strong>.</p><pre>screen/<br>  list/<br>    ├── ListRoute.kt       ← Navigation logic<br>    ├── ListScreen.kt      ← Pure UI<br>    ├── ListViewModel.kt   ← Business logic<br>    └── components/</pre><ul><li><strong>Route files</strong> (ListRoute.kt) handle navigation state, ViewModel creation, and state collection.</li><li><strong>Screen files</strong> (ListScreen.kt) are pure composables that receive data and callbacks — they know nothing about navigation.</li></ul><p>This makes your screens <strong>testable</strong> and <strong>reusable</strong>. You can fully preview ListScreen in Android Studio without setting up any mock navigation hosts.</p><h3>How Navigation Actually Works — A Visual Walkthrough</h3><p>Let’s trace what happens when a user navigates through the app:</p><pre>1. App launches<br>   BackStack: [ListRoute]<br>   Screen: ListScreen<br><br>2. User taps &quot;Raja Ampat&quot;<br>   backStack.add(DetailRoute(itemId = 1))<br>   BackStack: [ListRoute, DetailRoute(1)]<br>   Screen: DetailScreen (Raja Ampat)<br><br>3. User presses back<br>   backStack.removeLastOrNull()<br>   BackStack: [ListRoute]<br>   Screen: ListScreen<br><br>4. User taps profile icon<br>   backStack.add(AboutRoute)<br>   BackStack: [ListRoute, AboutRoute]<br>   Screen: AboutScreen</pre><p>It’s just a list. Push, pop. That’s it. No hidden state, no magic.</p><h3>Integrating ViewModel</h3><p>Navigation 3 works seamlessly with Jetpack ViewModel. In the route, we create it using Compose’s viewModel() function:</p><pre>entry&lt;ListRoute&gt; {<br>    val viewModel: ListViewModel = viewModel()<br>    val destinations by viewModel.destinations.collectAsStateWithLifecycle()<br>    // ...<br>}</pre><p>The ViewModel is scoped to the entry’s lifecycle, so it survives configuration changes but gets properly cleared when you pop the screen off the back stack.</p><h3>Summary: Navigation 2 vs Navigation 3 Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpbvEZ1PfbJ6Zj7tA8hBIA.png" /></figure><h3>My Recommendations</h3><p>After building this project with Navigation 3, here are my practical recommendations:</p><h4>1. Separate Route from Screen</h4><p>Keep navigation logic in *Route.kt files and UI in *Screen.kt files. This makes your screens testable and previewable.</p><h4>2. Always Use dropUnlessResumed for Navigation</h4><p>Wrap every navigation callback with dropUnlessResumed to prevent duplicate navigation when users tap quickly.</p><h4>3. Handle Invalid Arguments Gracefully</h4><p>As shown in detailRoute, always handle the case where arguments don&#39;t match valid data. Show an error screen instead of crashing.</p><h4>4. Keep Screens Pure: Don’t Pass the BackStack Down</h4><p>A common mistake is passing the backStack down into every single Composable. Instead, pass the backStack <em>only</em> to your high-level route handlers (like listRoute). Let these handlers translate navigation actions into simple lambda callbacks (e.g., onItemClick = { id -&gt; }) for your pure UI screens. This keeps your screens completely unaware of the navigation library.</p><h4>5. Start Simple</h4><p>Navigation 3 is designed to be incrementally adoptable. Start with basic push/pop navigation, and explore advanced features once you’re comfortable.</p><h3>Conclusion</h3><p>Jetpack Navigation 3 is a breath of fresh air. It feels like navigation was finally designed <em>for</em> Compose rather than <em>adapted to</em> Compose. The API is small, predictable, and gives you full control.</p><p>If you’re starting a new Compose project, I highly recommend using Navigation 3 from day one. If you have an existing app with Navigation 2, consider migrating screen by screen — the two can coexist during migration.</p><p>The full source code for this article is available on GitHub:</p><p>👉 <a href="https://github.com/amary21/MyCompose">github.com/amary21/MyCompose</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd34c70d6300" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/stop-fighting-your-navigation-library-a-practical-guide-to-jetpack-navigation-3-dd34c70d6300">Stop Fighting Your Navigation Library: A Practical Guide to Jetpack Navigation 3</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Room Isn’t Enough: Handling Encrypted Database Corruption in Production]]></title>
            <link>https://taufik-amary.medium.com/room-isnt-enough-handling-encrypted-database-corruption-in-production-e1a8766fd58c?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a8766fd58c</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[sqlcipher]]></category>
            <category><![CDATA[room-database]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Sun, 03 May 2026 13:01:01 GMT</pubDate>
            <atom:updated>2026-05-03T13:01:01.618Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Fixing SQLiteNotADatabaseException (Code 26) in Room + SQLCipher and preventing Android crash loops</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNzgQ4AcX6ASePcK9r-ryg.png" /></figure><p>This is not a typical tutorial. This is a note from a real situation where Crashlytics in production suddenly spiked, a hotfix had to be released immediately, and one question arose, is there a way for the application to recover itself without asking the user to clear data?</p><h3>Background</h3><p>One day Crashlytics showed an unusual spike in crashes. Not random, this happened massively in production, meaning many users were affected and couldn’t open the application at all.</p><p>After investigation, the root cause was database corruption in a Room DB encrypted with SQLCipher. The database file couldn’t be opened, Room threw an exception, the application crashed, and users were stuck in a crash loop.</p><p>The quickest solution that came to mind was asking users to clear data. But that’s not a solution, it’s an insult to UX. That’s where I started thinking, there must be a mechanism where the app can detect this condition and recover itself automatically.</p><h3>Why Can a Database Become Corrupted?</h3><p>Before going into the solution, it’s important to understand the causes. There are several scenarios that can make an encrypted database unreadable:</p><ul><li>Hardware failure during disk write operations</li><li>Rotation or loss of the master key in Android Keystore System</li><li>Invalid passphrase when opening SQLCipher</li><li>External interference, internal file modified by user or another app</li><li>Encryption migration, old plaintext file read by a newer encrypted version</li></ul><p>In an encrypted storage environment, even a single bit of corruption is enough to make the entire data undecryptable. If not anticipated, the application will be stuck in a crash loop that permanently locks the user out.</p><h3>Part 1: Fixing Room DB (Main Problem)</h3><h4>Wrong Initial Assumption</h4><p>The first step I took was to check whether Room already had a built-in mechanism for this. It turns out it does:</p><p>SupportSQLiteOpenHelper.Callback.onCorruption()</p><p>Great, problem solved, or so I thought. It wasn’t. After implementation and testing, onCorruption was never called.</p><p>After deeper investigation, I found the reason: the error that occurred in production was SQLiteNotADatabaseException with Error Code 26, file is not a database. This is not considered corruption in SQLite’s definition. This is a condition where the file is not recognized as a valid database at all, for example when a plaintext file is opened using SQLCipher. Room does not treat this as corruption, so onCorruption is never triggered.</p><p>I needed a different approach.</p><h3>Solution: Intercept at Factory Level</h3><p>If Room cannot detect this condition, I need to intercept the error before Room throws it upwards. The approach is to create a custom wrapper at the SupportSQLiteOpenHelper level, the earliest point where the database is opened.</p><pre>class SafeSupportOpenHelperFactory(<br>    private val passphrase: ByteArray,<br>    private val databaseName: String,<br>    private val onRecreate: () -&gt; Unit = {}<br>) : SupportSQLiteOpenHelper.Factory {<br><br>    override fun create(<br>        configuration: SupportSQLiteOpenHelper.Configuration<br>    ): SupportSQLiteOpenHelper {<br>        return SafeSupportOpenHelper(<br>            configuration = configuration,<br>            passphrase = passphrase,<br>            dbName = databaseName,<br>            onRecreate = onRecreate<br>        )<br>    }<br>}</pre><pre>class SafeSupportOpenHelper(<br>    private val configuration: SupportSQLiteOpenHelper.Configuration,<br>    private val passphrase: ByteArray,<br>    private val dbName: String,<br>    private val onRecreate: () -&gt; Unit<br>) : SupportSQLiteOpenHelper {<br><br>    private var _delegate: SupportSQLiteOpenHelper? = null<br><br>    private val delegate: SupportSQLiteOpenHelper<br>        get() = _delegate ?: SupportOpenHelperFactory(passphrase)<br>            .create(configuration)<br>            .also { _delegate = it }<br><br>    override val databaseName: String = dbName<br><br>    override fun setWriteAheadLoggingEnabled(enabled: Boolean) {<br>        delegate.setWriteAheadLoggingEnabled(enabled)<br>    }<br><br>    override val writableDatabase: SupportSQLiteDatabase<br>        get() = try {<br>            delegate.writableDatabase<br>        } catch (e: SQLiteNotADatabaseException) {<br>            handleCorruptedOrInvalid()<br>            delegate.writableDatabase<br>        } catch (e: Exception) {<br>            if (e.message?.contains(&quot;code 26&quot;) == true) {<br>                handleCorruptedOrInvalid()<br>                delegate.writableDatabase<br>            } else throw e<br>        }<br><br>    override val readableDatabase: SupportSQLiteDatabase<br>        get() = writableDatabase<br><br>    override fun close() {<br>        _delegate?.close()<br>        _delegate = null<br>    }<br><br>    private fun handleCorruptedOrInvalid() {<br>        onRecreate()<br>        _delegate?.close()<br>        _delegate = null<br><br>        configuration.context.getDatabasePath(dbName)?.let { dbFile -&gt;<br>            listOf(<br>                dbFile,<br>                File(&quot;${dbFile.path}-shm&quot;),<br>                File(&quot;${dbFile.path}-wal&quot;)<br>            ).forEach { it.delete() }<br>        }<br>    }<br>}</pre><p>⚠️ Important detail that is often overlooked: Do not only delete the .db file. Auxiliary files .db-wal (Write-Ahead Log) and .db-shm (Shared Memory) must also be deleted. Leaving these files will cause new errors when the database is reinitialized.</p><p>There is another important detail: since delegate is reset to null after handleCorruptedOrInvalid(), a new instance will be created when delegate.writableDatabase is called again, fresh, without state from the previous failed instance. This is why we should not use lazy for delegate.</p><h3>Setup in Dependency Injection</h3><pre>val dataBaseModule = module {<br><br>    single&lt;SupportSQLiteOpenHelper.Factory&gt; {<br>        val passphrase = &quot;your_passphrase&quot;.toByteArray(StandardCharsets.UTF_8)<br><br>        SafeSupportOpenHelperFactory(<br>            passphrase = passphrase,<br>            databaseName = &quot;photo_database.db&quot;,<br>            onRecreate = {<br>                FirebaseCrashlytics.getInstance()<br>                    .recordException(Exception(&quot;DB corrupted, auto-recreating&quot;))<br>            }<br>        )<br>    }<br><br>    single {<br>        Room.databaseBuilder(<br>            get&lt;Application&gt;(),<br>            PhotoRoomDatabase::class.java,<br>            &quot;photo_database.db&quot;<br>        )<br>            .openHelperFactory(get())<br>            .fallbackToDestructiveMigration(true)<br>            .build()<br>    }<br><br>    single { get&lt;PhotoRoomDatabase&gt;().photoDao() }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbQz2Uuuv7bJvmNE8MWARg.png" /></figure><h3>Part 2: Checking DataStore and Finding the Same Issue</h3><p>After fixing Room, I started wondering about Jetpack DataStore, which is also encrypted. Does it already have a fallback mechanism? My initial assumption was yes. It turned out no.</p><h4>Wrong Assumption Again</h4><p><em>ReplaceFileCorruptionHandler</em> only catches CorruptionException thrown explicitly by the Serializer, not GeneralSecurityException from Tink decryption failures. This means that if an old plaintext file is read by a new encrypted serializer, the app will crash because the exception is not handled. The pattern is the same as Room, the built-in handler has a blind spot.</p><h3>Encryption Setup with Tink</h3><p>From DataStore version 1.2.x, Google provides datastore-tink, which is more secure than manual implementation since Tink is cryptographically audited.</p><p>One crucial thing: Tink must be initialized before use.</p><pre>class MainApplication : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        AeadConfig.register()<br>        startKoin { ... }<br>    }<br>}</pre><h3>Solution: Fallback Directly in Serializer</h3><p>Since ReplaceFileCorruptionHandler is not enough, fallback must be handled directly inside readFrom().</p><pre>class EncryptedPhotoStoreSerializer(<br>    private val json: Json = Json { ignoreUnknownKeys = true },<br>    private val context: Context<br>) : Serializer&lt;PhotoStoreData&gt; {<br><br>    private val fileName = &quot;photo_store.json&quot;<br><br>    private val aead: Aead by lazy {<br>        val keysetHandle = AndroidKeysetManager.Builder()<br>            .withSharedPref(context, &quot;photo_keyset&quot;, &quot;photo_keyset_prefs&quot;)<br>            .withKeyTemplate(KeyTemplate.createFrom(PredefinedAeadParameters.AES256_GCM))<br>            .withMasterKeyUri(&quot;android-keystore://photo_master_key&quot;)<br>            .build()<br>            .keysetHandle<br>        keysetHandle.getPrimitive(RegistryConfiguration.get(), Aead::class.java)<br>    }<br><br>    override val defaultValue = PhotoStoreData()<br><br>    override suspend fun readFrom(input: InputStream): PhotoStoreData =<br>        try {<br>            val encryptedBytes = input.readBytes()<br>            if (encryptedBytes.isEmpty()) return defaultValue<br>            val decrypted = aead.decrypt(encryptedBytes, fileName.encodeToByteArray())<br>            json.decodeFromString(decrypted.decodeToString())<br>        } catch (e: GeneralSecurityException) {<br>            Log.e(&quot;DataStore&quot;, &quot;Decryption failed, wiping file: ${e.message}&quot;)<br>            wipeFile()<br>            defaultValue<br>        } catch (e: SerializationException) {<br>            Log.e(&quot;DataStore&quot;, &quot;Deserialization failed: ${e.message}&quot;)<br>            wipeFile()<br>            defaultValue<br>        } catch (e: Exception) {<br>            Log.e(&quot;DataStore&quot;, &quot;Unknown error: ${e.message}&quot;)<br>            defaultValue<br>        }<br><br>    override suspend fun writeTo(t: PhotoStoreData, output: OutputStream) {<br>        withContext(Dispatchers.IO) {<br>            val jsonBytes = json.encodeToString(t).encodeToByteArray()<br>            val encrypted = aead.encrypt(jsonBytes, fileName.encodeToByteArray())<br>            output.write(encrypted)<br>        }<br>    }<br><br>    private fun wipeFile() {<br>        context.filesDir<br>            .resolve(&quot;datastore/$fileName&quot;)<br>            .also { if (it.exists()) it.delete() }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3odsynYduO0F9xJbKJ9D9Q.png" /></figure><h3>Comparison: Built-in Handler vs Reality</h3><pre>| Component           | Built-in Handler             | Enough? | Solution                     |<br>|---------------------|------------------------------|---------|------------------------------|<br>| Room + SQLCipher    | onCorruption()               | No      | SafeSupportOpenHelper        |<br>| DataStore + Tink    | ReplaceFileCorruptionHandler | No      | Fallback in readFrom()       |</pre><h3>Key Takeaways</h3><ol><li>Do not assume built-in handlers are enough</li><li>Intercept as close as possible to the error source</li><li>Always delete auxiliary SQLite files</li><li>Zero changes in upper layers is a good sign</li><li>Always log to Crashlytics</li></ol><blockquote>This article was born from a real production issue. Hopefully it helps anyone facing a similar situation, especially when dealing with crash spikes and needing to ship a hotfix quickly.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a8766fd58c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Defaulting to WebSocket: Building Event-Driven UI with Firebase Cloud Messaging]]></title>
            <link>https://taufik-amary.medium.com/stop-defaulting-to-websocket-building-event-driven-ui-with-firebase-cloud-messaging-34596c16e601?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/34596c16e601</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 01:02:03 GMT</pubDate>
            <atom:updated>2026-01-26T01:02:03.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYopjSdVd8JvMJ1uTiRTFQ.png" /></figure><blockquote><em>“Sometimes the best solution isn’t the most advanced one — it’s the one you already have.”</em></blockquote><p>Stop automatically suggesting WebSocket every time there’s a need for real-time UI updates. <strong>Not every problem requires the most complex solution.</strong></p><p>Imagine a simple scenario: a user is on a <strong>“Waiting for Payment”</strong> screen, and when the payment succeeds, the screen automatically updates without the user pressing a refresh button or taking any action.</p><p>That’s it. That simple.</p><p>Yet the common developer reflex is:</p><blockquote><em>“Just use WebSocket.”</em></blockquote><p>But the real question isn’t only <em>“Can we implement WebSocket?”</em><br> It’s also:</p><ul><li>Is the infrastructure ready for it?</li><li>Is the complexity justified?</li><li>Is there a simpler approach already available?</li></ul><h4>The Hidden Cost of “Just Use WebSocket”</h4><p>If your system doesn’t already support WebSocket, introducing it means:</p><ul><li>Infrastructure team must provision and monitor persistent connections.</li><li>Backend must handle connection lifecycle, scaling, retries, and state.</li><li>Mobile apps must add libraries, manage connection reliability, reconnection logic, and edge cases.</li><li>Android and iOS implementations often differ.</li><li>Debugging becomes harder across environments.</li></ul><p>For a requirement as small as:</p><blockquote><em>“Update the UI when the payment succeeds”</em></blockquote><p>…this is often <strong>overkill</strong>.</p><h4>The Overlooked Infrastructure You Already Have</h4><p>Almost every modern application — especially transactional ones — already relies on:</p><p><strong>Push Notifications (Firebase Cloud Messaging / APNS)</strong></p><p>Usually, push notifications are only treated as a user-facing feature:</p><blockquote><em>“Show a banner when something happens.”</em></blockquote><p>But with the right approach, they can become the backbone of an <strong>Event-Driven UI</strong> system:</p><blockquote><em>“The server emits events, and the app reacts by updating its UI automatically — without user interaction.”</em></blockquote><h3>What is Event-Driven UI?</h3><p>Event-Driven UI is an architectural pattern where the <strong>server sends events to the mobile app</strong>, and the app responds by automatically updating the UI — without any user action.</p><pre>Server ──▶ FCM ──▶ Mobile App ──▶ UI Update</pre><p>Unlike traditional approaches:</p><ul><li><strong>Polling</strong>: Mobile app constantly queries the server (resource-intensive)</li><li><strong>Manual refresh</strong>: Waiting for user to press a button</li><li><strong>WebSocket</strong>: Complex, requires new infrastructure</li></ul><p>With Event-Driven UI, the <strong>server proactively notifies</strong> the app when to update.</p><h3>Why FCM, Not WebSocket?</h3><pre>| Aspect          | WebSocket                     | FCM                     |<br>|-----------------|-------------------------------|-------------------------|<br>| Infrastructure  | Requires new setup            | Already exists          |<br>| Connection      | Persistent, needs maintenance | Managed by Google/Apple |<br>| Battery         | Drains if not optimized       | Highly efficient        |<br>| Scaling         | Complex                       | Handled by Firebase     |<br>| Cross-platform  | Different implementations     | Single API              |</pre><p>FCM has become the <strong>de facto standard</strong> for push notifications. Its infrastructure is mature, reliable, and — most importantly — <strong>already in your application</strong>.</p><h3>High-Level Architecture</h3><p>This implementation uses <strong>Kotlin Multiplatform + Compose Multiplatform</strong>, but the concept applies equally to Flutter, React Native, SwiftUI, or native Android.</p><pre>Compose UI<br>   ↓ observes<br>ViewModel<br>   ↓ observes<br>AppStateManager (shared state)<br>   ↑ updated by<br>EventHandler<br>   ↑ triggered by<br>FCM Manager (platform-specific)<br>   ↑ receives from<br>Firebase / APNS<br>   ↑ sent by<br>Backend (Firebase Admin SDK)</pre><h3>Key Components</h3><h4><strong>1. Event Types</strong></h4><p>Define the event contract between server and mobile:</p><pre>enum class EventType {<br>    PAYMENT_SUCCESS, PAYMENT_FAILED,<br>    BALANCE_UPDATED, REFRESH_HOME,<br>    NEW_PROMOTION, SECURITY_ALERT,<br>    // ... and more<br>}</pre><h4>2. AppStateManager (Singleton)</h4><p>Central state observed by ViewModels. <strong>Must be a singleton</strong> so FCM and ViewModel access the same instance.</p><pre>class AppStateManager {<br>    private val _lastNotification = MutableStateFlow&lt;NotificationData?&gt;(null)<br>    val lastNotification = _lastNotification.asStateFlow()<br>    <br>    fun updateLastNotification(notification: NotificationData) {<br>        _lastNotification.value = notification<br>    }<br>}</pre><h4>3. ViewModel with Reactive State</h4><p>ViewModel observes AppStateManager and automatically reacts when a notification arrives:</p><pre>stateManager.lastNotification.collect { notification -&gt;<br>    if (notification?.getEventType() == EventType.PAYMENT_SUCCESS) {<br>        // Trigger UI update!<br>    }<br>}</pre><h4>4. Platform FCM Manager</h4><p>Platform-specific implementation using the KMP pattern:</p><ul><li><strong>Android</strong>: Uses FirebaseMessaging directly</li><li><strong>iOS</strong>: Uses Firebase via CocoaPods</li></ul><p>Both call the same EventHandler in shared code.</p><h4>5. Backend (Ktor + Firebase Admin SDK)</h4><p>Server sends FCM with a data payload containing eventType. Response is returned immediately, while FCM is sent asynchronously in the background.</p><h3>Demo Flow: Payment Success</h3><ol><li>User opens <strong>Waiting for Payment</strong></li><li>Backend confirms payment success</li><li>Server sends FCM event: PAYMENT_SUCCESS</li><li>Mobile receives the event</li><li>AppStateManager updates state</li><li>ViewModel reacts</li><li>UI automatically transitions to success screen</li></ol><p><strong>User does nothing. UI updates by itself.</strong></p><h3>Silent vs Non-Silent Notifications</h3><pre>| Mode       | Behavior                                       | Use Case                     |<br>|------------|------------------------------------------------|------------------------------|<br>| Silent     | No banner, only triggers background processing | Balance update, data refresh |<br>| Non-Silent | Shows notification banner                      | Payment success, new promo   |</pre><blockquote>⚠️ Note: Silent notifications (especially on iOS) are subject to system limitations and delivery is not strictly guaranteed in real-time. This approach works best for <strong>eventual consistency</strong>, not ultra-low latency systems.</blockquote><h3>When to Still Use WebSocket?</h3><p>This approach is not anti-WebSocket. It’s anti <strong>unnecessary WebSocket</strong>.</p><pre>| Use Case           | Recommendation |<br>|--------------------|----------------|<br>| Real-time chat     | WebSocket      |<br>| Live streaming     | WebSocket      |<br>| Multiplayer gaming | WebSocket      |<br>| Payment status     | FCM            |<br>| Balance update     | FCM            |<br>| Order tracking     | FCM            |</pre><p>If your updates are occasional and not latency-critical to the millisecond, FCM is usually more pragmatic.</p><h3>Conclusion</h3><p>Event-Driven UI with FCM is an approach that is:</p><ul><li><strong>Pragmatic</strong> — Uses existing infrastructure</li><li><strong>Efficient</strong> — No need to maintain persistent connections</li><li><strong>Cross-platform</strong> — Single logic for Android and iOS</li><li><strong>Scalable</strong> — Firebase handles it</li></ul><p>Before jumping to “use WebSocket”, ask yourself:</p><ul><li>Is the infrastructure ready?</li><li>Is the complexity worth it?</li><li><strong>Is there a simpler solution?</strong></li></ul><p>Sometimes, the best solution is the one <strong>already in front of you</strong>.</p><p><em>This article is based on a real implementation using Kotlin Multiplatform and Compose Multiplatform. Source code available on </em><a href="https://github.com/amary21/AmaryPay.git"><em>GitHub</em></a><em>.</em></p><h3>📫 Let’s Connect</h3><ul><li>📧 Email: <a href="http://taufik.amary@gmail.com/">taufik.amary@gmail.com</a></li><li>💻 GitHub: <a href="https://github.com/amary21">github.com/amary21</a></li><li>💼 LinkedIn: <a href="http://www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34596c16e601" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming Bazel Dependency Conflicts: An Android Case Study]]></title>
            <link>https://proandroiddev.com/taming-bazel-dependency-conflicts-an-android-case-study-44b7926839be?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b7926839be</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[build-system]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[bazel]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 00:01:55 GMT</pubDate>
            <atom:updated>2026-10-12T23:38:03.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQJUolgtfxv52dg2COK82w.png" /><figcaption>Illustration Generated by Gemini</figcaption></figure><p>For many developers, “dependency conflict” is a phrase that instantly causes a headache. This is especially true when moving from a familiar ecosystem like Gradle to a powerful but complex tool like Bazel.</p><p>A while back, I wrote about my experience building an Android app with Bazel (You can read about it here: <a href="https://medium.com/@taufik.amary/building-a-modern-android-music-player-app-with-bazel-jetpack-compose-and-exoplayer-4a70039655f2">Building a Modern Android Music Player App with Bazel…</a>).</p><p>Recently, I decided to update some libraries in that project, most notably by moving to the Compose BOM (androidx.compose:compose-bom:2024.12.01).</p><h3>🧨 The Problem Begins: A Simple Library Update</h3><p>I updated my MODULE.bazel file with the new dependencies. The initial attempt looked something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab6ac611fb4ff73c1120f2dba1a8df3e/href">https://medium.com/media/ab6ac611fb4ff73c1120f2dba1a8df3e/href</a></iframe><p>I ran the build, and… it failed. I was greeted by a long, cryptic error log, which boiled down to a classic dependency conflict.</p><p>Here’s just a small snippet of the dependency graph hell:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Wna5GjBr3RBP9sCXswiAA.png" /></figure><p>At its core, the problem was familiar. For example, looking at the log:</p><ul><li>androidx.activity:activity-compose:1.7.0 (which I was using) explicitly wants androidx.compose.ui:ui:1.0.1.</li><li>But the new Compose BOM (2024.12.01) was pulling in androidx.compose.ui:ui:1.7.6 (a much newer version).</li></ul><p>This threw me for a loop. In my time with Gradle, I rarely faced conflicts this severe. Gradle usually seems “smart” enough to just pick the newest version and move on.</p><h3>🧠 Understanding the “Why”: Gradle vs. Bazel</h3><p>After some digging, I realized the fundamental difference lies in how these build tools manage versions.</p><h4>1. Gradle: “Newest Version Wins” (By Default)</h4><p>Gradle, by default, uses a “Newest Version Selection” strategy. If it encounters a conflict, it simply picks the <strong>newest</strong> version of the dependency available in the graph.</p><ul><li>A → C v1.0</li><li>B → C v2.0</li><li><strong>Gradle’s Result:</strong> C v2.0 (Chosen automatically)</li></ul><h4>2. Bazel (Bzlmod): “Minimal Version Selection” (MVS)</h4><p>Bazel, with the introduction of Bzlmod, adopts the “Minimal Version Selection” (MVS) algorithm, which is also used by Go modules (you can read the official documentation on Bzlmod <a href="https://bazel.build/external/module">here</a>).</p><p><strong>MVS Principle:</strong> Bazel selects the <strong>minimum</strong> version that satisfies <strong>all</strong> constraints in the dependency graph. This algorithm is highly deterministic and reproducible.</p><p>Let’s look at the classic example from the Bazel documentation:</p><pre>       A 1.0<br>      /     \<br>   B 1.0    C 1.1<br>     |        |<br>   D 1.0    D 1.1</pre><p>In this case, Bazel will select D 1.1. Why? Because it&#39;s the <em>highest</em> version <em>explicitly required</em> by a module (C 1.1 needs it). It&#39;s &quot;minimal&quot; because D 1.1 is the earliest version that satisfies all requirements. Even if D 1.2 existed, MVS would <em>not</em> pick it unless another module explicitly asked for it.</p><p><strong>Quick Comparison</strong></p><pre>| Aspect                     | Gradle (Default)         | Bazel (MVS)                                |<br>|----------------------------|--------------------------|--------------------------------------------|<br>| Algorithm                  | Newest Version Selection | Minimal Version Selection                  |<br>| Version Choice             | Newest version found     | Minimum version that meets all constraints |<br>| Example (D 1.0 vs 1.1).    | D 1.1 selected           | D 1.1 selected                             |<br>| If D 1.2 is available      | D 1.2 selected           | D 1.1 is still selected                    |<br>| Reproducibility            | Medium                   | Very High                                  |</pre><p>My conflict was happening because MVS couldn’t find a <em>single</em> version that satisfied all the different version ranges being requested.</p><h3>🧩 The Solution: Finding and Fixing the Conflicts</h3><p>So, how do we fix this?</p><p>A lot of advice online (even from our new AI overlords like ChatGPT, Claude, Gemini, etc.) will tell you to just add version_conflict_policy = &quot;pinned&quot; to your maven.install.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fdc2761fcc350867ff26bbbcfdd9b50/href">https://medium.com/media/7fdc2761fcc350867ff26bbbcfdd9b50/href</a></iframe><p>However, <strong>this is not enough.</strong> This policy only tells Bazel to “pin” the versions it <em>successfully</em> resolves; it doesn’t actually <em>solve</em> the conflict itself. You will still get the same error.</p><p>After digging into the rules_jvm_external repository, I found the real solution: using maven.artifact to manually &quot;force&quot; or &quot;override&quot; the version of a specific library.</p><p>But… how do we know <em>which</em> versions to pick when the error log is so noisy?</p><h4>Step 1: Debug and Pin Dependencies</h4><p>The key is to run this command (from rules_jvm_external) to perform the pinning process and dump the <em>full</em> log:</p><pre>bazel clean --expunge<br>bazel run @maven//:pin &amp;&gt; maven_pin.txt</pre><p>This command runs the dependency resolution process and saves <em>all</em> output (including the detailed errors) to a file named maven_pin.txt.</p><h4>Step 2: Analyze the Log</h4><p>Now, open maven_pin.txt. Scroll up from the bottom (or search for &quot;Conflicting dependencies&quot;) until you find the root of the problem. In my case, the log looked like this:</p><pre>...<br>Resolution error: Conflicting dependencies:<br>androidx.collection:collection:1.0.0 or 1.1.0 or 1.2.0 or 1.4.0 or 1.4.2 or [1.2.0] wanted by<br><br> androidx.activity:activity:1.7.0 wants 1.0.0<br> ├─ androidx.activity:activity-ktx:1.7.0 wants androidx.activity:activity:[1.7.0]<br>...</pre><p>The culprit was clear: androidx.collection:collection. Many different dependencies were requesting many different versions.</p><h4>Step 3: Define a Version and Apply the Override</h4><p>Now that we know the conflicting library, we can pick one version to rule them all.</p><ol><li><strong>The Strategy:</strong> Try picking the <strong>newest</strong> version listed in the conflict log (in this case, 1.4.2). The assumption is that this version is backward-compatible and will satisfy all modules.</li><li>If the newest version still causes errors, try the next-newest version and repeat.</li></ol><p>Add this override to your MODULE.bazel file, <strong>before</strong> the maven.install block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8acb092725a9b03da50a68e93bc2bbe/href">https://medium.com/media/f8acb092725a9b03da50a68e93bc2bbe/href</a></iframe><h4>Step 4: Iterate and Repeat</h4><p>Run the bazel run @maven//:pin &amp;&gt; maven_pin.txt command again. Check the maven_pin.txt file. If another conflict appears for a <em>different</em> library, repeat Steps 2 and 3 for that library.</p><p>For my project, I ended up needing to override several libraries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228e70c19e2f006f69e25dea8dce9f19/href">https://medium.com/media/228e70c19e2f006f69e25dea8dce9f19/href</a></iframe><p>After adding all the necessary overrides, the bazel run @maven//:pin command should finally run successfully with no errors.</p><h3>✅ The Final Result</h3><p>Now, I could run my project’s build commands as usual:</p><pre>bazel build //app/src/main:app<br>adb install -r bazel-bin/app/src/main/app.apk<br>adb shell am start -n com.amary.my.music/.MainActivity</pre><p>And… voilà!<br> The app built and ran perfectly with all updated dependencies 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*I3AFxIqINAVY4Va55IMMUQ.png" /></figure><p>📦 Source code available here:<br> 👉 <a href="https://github.com/amary21/my-music-bazel">github.com/amary21/my-music-bazel</a></p><h3>💡Final Thoughts</h3><p>Bazel’s MVS dependency resolution can feel “noisy” and rigid at first, especially when compared to Gradle’s “it-just-works” approach. However, its deterministic and reproducible nature is invaluable for build consistency in the long run. The solution is to be explicit and provide manual overrides when MVS can’t find a path.</p><p>One thing I’m still figuring out is the best way to manage updates to the Bazel <em>rules</em> themselves (like rules_android, rules_kotlin). Updating these often introduces significant configuration changes, sometimes even requiring a Bazel version bump. That&#39;s why I&#39;m still using the 2024 version of the Compose BOM in this project; the 2025 version requires at least Kotlin 2, and its compiler has moved to JetBrains, which would necessitate a tricky update to rules_kotlin.</p><p>If you have any experience or tips on managing Bazel rule updates, I’d love to hear them in the comments below!</p><h3><strong>📫 Let’s Connect</strong></h3><ul><li>📧 Email: <a href="http://taufik.amary@gmail.com/">taufik.amary@gmail.com</a></li><li>💻 GitHub: <a href="https://github.com/amary21">github.com/amary21</a></li><li>💼 LinkedIn: <a href="http://www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b7926839be" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/taming-bazel-dependency-conflicts-an-android-case-study-44b7926839be">Taming Bazel Dependency Conflicts: An Android Case Study</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD for Android Kotlin: The Easy Way with Jenkins Freestyle Project (JaCoCo + Detekt)]]></title>
            <link>https://taufik-amary.medium.com/ci-cd-for-android-kotlin-the-easy-way-with-jenkins-freestyle-project-jacoco-detekt-c886dc8ac399?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c886dc8ac399</guid>
            <category><![CDATA[detekt]]></category>
            <category><![CDATA[jacoco]]></category>
            <category><![CDATA[ci-cd-devops]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 00:01:52 GMT</pubDate>
            <atom:updated>2025-10-20T00:01:52.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*MMu1O4A7IMw7_9GUixf9dw.png" /></figure><p>In this article, I’ll share my experience implementing CI/CD for an Android Kotlin project using Jenkins Freestyle Project. This pipeline focuses on test automation with JaCoCo and static code analysis using Detekt.</p><p>Why Freestyle Project? It’s easier to configure through the Jenkins UI, perfect for those new to CI/CD or who prefer visual configuration without coding Jenkinsfiles.</p><h3>Prerequisites</h3><p>Before we start, ensure you have:</p><ol><li>A running Jenkins server.</li><li>An Android Kotlin project hosted on a Git repository (e.g., GitHub, GitLab).</li><li>The following Jenkins plugins installed:</li></ol><ul><li>JUnit Plugin</li><li>Coverage Plugin</li><li>Warnings Next Generation</li><li>HTML Publisher</li><li>Gradle Plugin (usually included by default)</li></ul><h3>Tools &amp; Plugins Used</h3><p>This section now focuses only on the Gradle-level tools, as the Jenkins plugins were covered above.</p><p><strong>Gradle Plugins:</strong></p><ul><li><strong>JaCoCo:</strong> Generates code coverage data.</li><li><strong>Detekt:</strong> Performs static code analysis.</li></ul><h3>Gradle Setup</h3><p><strong>JaCoCo Configuration</strong></p><p>Add this to your build.gradle.kts (app level) file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/435eee4cf93a441729823201eb617c7a/href">https://medium.com/media/435eee4cf93a441729823201eb617c7a/href</a></iframe><p><strong>Note:</strong> The fileFilterExcludeJacoco is crucial. It excludes auto-generated Android files (like R.class, BuildConfig, etc.) from the coverage report. This ensures your metrics reflect only the code you&#39;ve actually written.</p><p><strong>Detekt Configuration</strong></p><p>In build.gradle.kts (project level):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1c6281044486b686a2ef7bf7a7152d/href">https://medium.com/media/1f1c6281044486b686a2ef7bf7a7152d/href</a></iframe><p>In build.gradle.kts (app level):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba724b9cd59c6d670578356f084973a/href">https://medium.com/media/bba724b9cd59c6d670578356f084973a/href</a></iframe><h3>Jenkins Freestyle Project Configuration</h3><p>Now, let’s set up the job in Jenkins.</p><h4>1. Create New Freestyle Project</h4><ul><li>Dashboard → New Item</li><li>Enter project name: “MobileAndroid”</li><li>Select <strong>Freestyle project</strong> → OK</li></ul><h4>2. Source Code Management</h4><ul><li>Select <strong>Git</strong></li><li><strong>Repository URL:</strong> <a href="https://github.com/username/AeonCard.git">https://github.com/username/MobileAndroid.git</a></li><li><strong>Credentials:</strong> Add your GitHub/Git credentials.</li><li><strong>Branch:</strong> */main</li></ul><h4>3. Build Steps</h4><p>Here, we’ll add our preparation script and run our Gradle tasks.</p><h4><strong>Step 1: Prepare Environment (Execute shell)</strong></h4><p>The first and most crucial step is to prepare the build environment. Add an <strong>“Execute shell”</strong> build step and insert the following script. This will create the essential local.properties file and print environment information for debugging.</p><pre>#!/bin/bash<br>set -e<br><br># Create local.properties to point to the Android SDK location in the Jenkins environment<br>echo &quot;sdk.dir=/opt/android-sdk&quot; &gt; local.properties<br><br># Print environment info for debugging purposes<br>echo &quot;=== Environment Info ===&quot;<br>echo &quot;ANDROID_HOME: $ANDROID_HOME&quot;<br>echo &quot;ANDROID_SDK_ROOT: $ANDROID_SDK_ROOT&quot;<br>echo &quot;Java Version:&quot;<br>java -version<br>echo &quot;========================&quot;</pre><h4><strong>Step 2 : Run Gradle Tasks (Invoke Gradle script)</strong></h4><p>After the environment is ready, add <strong>“Invoke Gradle script”</strong> build steps. It’s best to separate each main task into its own step for easier failure tracking.</p><ul><li><strong>Step 2.1 — Clean:</strong></li><li>Tasks: clean</li><li><strong>Step 2.2 — Build:</strong></li><li>Tasks: assembleDebug</li><li><strong>Step 2.3 — Run Tests &amp; Generate Coverage:</strong></li><li>Tasks: jacocoTestReport (our custom .kts task)</li><li><strong>Step 2.5 — Static Analysis:</strong></li><li>Tasks: detekt</li></ul><h4>4. Post-build Actions</h4><p>This is where we publish our results to the Jenkins dashboard.</p><p><strong>Publish JUnit Results</strong></p><ul><li>Add post-build action: <strong>Publish JUnit test result report</strong></li><li>Test report XMLs: **/build/test-results/test*/**/*.xml</li></ul><p><strong>Record JaCoCo Coverage</strong></p><ul><li>Add post-build action: <strong>Record code coverage results</strong></li><li>Coverage Parser: <strong>JaCoCo Coverage Reports</strong></li><li>Report File Pattern: **/jacoco*.xml</li></ul><p><strong>Record Detekt Warnings</strong></p><ul><li>Add post-build action: <strong>Record compiler warnings and static analysis results</strong></li><li>Tool: <strong>Detekt</strong></li><li>Pattern: **/build/reports/detekt/*.xml</li></ul><p><strong>Publish HTML Reports</strong></p><p>Add post-build action: <strong>Publish HTML reports</strong> (add this action twice)</p><p><strong>JaCoCo Report:</strong></p><ul><li>HTML directory: app/build/reports/jacoco/jacocoTestReport/html</li><li>Index page: index.html</li><li>Report title: JaCoCo Test Coverage Report</li></ul><p><strong>Detekt Report:</strong></p><ul><li>HTML directory: app/build/reports/detekt</li><li>Index page: detekt.html</li><li>Report title: Detekt Static Analysis Report</li></ul><h3>Implementation Results</h3><p>After the pipeline runs, here are the results I achieved for the MobileAndroid project:</p><h4>Dashboard Overview</h4><p>Test Result Trend:</p><p>The graph shows 978 tests passing consistently, with 0 failures from build #24 to #36. Test duration holds steady at ~14 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*BlRWOmYhWdehb9l40OKz3Q.png" /></figure><p>Code Coverage Trend:</p><p>The trend graph shows that while coverage was maintained steadily at 68% (Line) and 66% (Branch) through build #33, it experienced a sharp decline starting at build #34. This highlights a recent regression in test quality that needs to be addressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*ipR7Dwhp4D2B-4DBiBee4w.png" /></figure><h3>Test Results Detail</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMAbM3wb66P70vH8FDXgGA.png" /></figure><h3>Coverage Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8zOAdmEzb2PKn6j5WbtNg.png" /></figure><h3>Detekt Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRJk-PhkZxMTH45oaHuaMQ.png" /></figure><h3>Best Practices</h3><ol><li><strong>Consistent Build Order:</strong> Always execute tasks in the same order (clean → build → test → reports) for predictable results.</li><li><strong>Multiple Report Formats:</strong> Generate XML (for Jenkins) and HTML (for humans) reports.</li><li><strong>Track Historical Trends:</strong> Monitor metrics over time to detect regressions early.</li><li><strong>Zero Warning Policy:</strong> Maintain a clean codebase by fixing static analysis warnings immediately.</li></ol><h3>Conclusion</h3><p>Implementing CI/CD with Jenkins Freestyle Project provides:</p><blockquote><strong>Benefits:</strong> easy configuration via UI, automated quality checks, fast feedback loop, clear visibility with dashboard, and stable and reliable builds</blockquote><p><strong>Why Freestyle vs. Pipeline:</strong></p><ul><li>Easier for beginners</li><li>No Groovy scripting required</li><li>Visual configuration</li><li>Perfect for standard workflows</li></ul><blockquote>With this setup, the development team can confidently make code changes knowing there’s a safety net of automated testing and quality checks running on every build.</blockquote><p><strong>📫 Let’s Connect</strong></p><ul><li>📧 Email: <a href="http://taufik.amary@gmail.com/">taufik.amary@gmail.com</a></li><li>💻 GitHub: <a href="https://github.com/amary21">github.com/amary21</a></li><li>💼 LinkedIn: <a href="http://www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c886dc8ac399" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More Than Copilot? Meet Kiro AI, the IDE with Built-in Intelligence]]></title>
            <link>https://taufik-amary.medium.com/more-than-copilot-meet-kiro-ai-the-ide-with-built-in-intelligence-af1c726bc4e9?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/af1c726bc4e9</guid>
            <category><![CDATA[spec-driven-development]]></category>
            <category><![CDATA[kiro]]></category>
            <category><![CDATA[productivity-tools]]></category>
            <category><![CDATA[ai-for-developers]]></category>
            <category><![CDATA[future-of-idea]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 17:36:37 GMT</pubDate>
            <atom:updated>2025-08-18T01:10:49.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j-SPKPJO9uAoVjpr" /><figcaption>Photo by <a href="https://unsplash.com/@djanmamur?utm_source=medium&amp;utm_medium=referral">Mamur Saitbaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you’re coding. Usually, when an error pops up, the ritual is clear: open a browser, start googling, check Stack Overflow, and try out various solutions until something works.</p><p>That routine is changing. AI has become the new “buddy” for developers. From Copilot to Gemini to Cursor — everyone is racing to be the smartest coding assistant.</p><p>And now, in the middle of all that noise, a new contender has arrived from AWS: <strong>Kiro AI</strong>.</p><h3>What Is Kiro AI?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*k3J37Sp_wQ9H8rlTg3pVUQ.png" /></figure><p>At first glance, Kiro looks a lot like VS Code. But here’s the catch: <strong>AI isn’t just an add-on — it’s built into the core of the editor.</strong></p><p>Kiro can:</p><ul><li>Read and understand your entire project</li><li>Explain confusing code in plain language</li><li>Assist with refactoring &amp; debugging</li><li>Even… run terminal commands automatically (imagine an AI that runs npm install or gradle build for you).</li></ul><p>It feels less like a smarter autocomplete and more like coding alongside an active partner.</p><h3>Why Is Kiro Different?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruP-YZqjI0qplJNrITc7mA.png" /></figure><h3>Why Is Kiro Different?</h3><p>Kiro isn’t just another “AI assistant inside your editor.” It’s designed as an <strong>AI-native coding environment</strong>, built to scale from quick prototypes to complex projects.</p><p>Here’s what makes it stand out:</p><ul><li>✍️ <strong>Bring Structure to AI Coding with Spec-Driven Development</strong><br> Kiro transforms your prompt into clear requirements, structured designs, implementation tasks validated by robust tests, and high-quality code. It’s AI coding, but with the maturity of real engineering practices.</li><li>🤖 <strong>Built from the Ground Up for Agents</strong><br> Multimodal chat, spec-driven workflows, and agent hooks are first-class citizens. Kiro is crafted for working <em>with</em> agents, giving you a new kind of development experience that still feels familiar.</li><li>📂 <strong>More Context, Less Repetition</strong><br> Thanks to specs, steering, and smart context management, Kiro understands the intent behind your prompts and helps you implement complex features on larger codebases — in fewer iterations.</li><li>🔗 <strong>Integrate Tools and Data with MCP</strong><br> Bring in your world: connect to docs, databases, APIs, and more with native MCP integration. No more copy-paste between tools — everything is right where you code.</li></ul><h3>But… There’s a Catch</h3><p>Two things make Kiro feel exclusive right now:</p><ol><li><strong>Not publicly released yet</strong> — access is limited to a waitlist</li><li><strong>Standalone editor</strong> — you’ll have to leave your favorite environment (like VS Code or IntelliJ) to use it</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NVincw8EmpyuO49oIU-Z9w.png" /></figure><p>So if you’re a developer who’s deeply attached to your current editor, switching may feel like a hurdle.</p><h3>Is It Worth Trying?</h3><p>If you’re an early adopter who loves exploring new tools, Kiro is definitely intriguing. It feels like a glimpse into the future of IDEs — where AI isn’t just an assistant, but the core of the coding experience.</p><p>But if you need stability, a large community, and wide integration support, Copilot or Cursor might still be the safer choice for daily use.</p><p>✦ <strong>In Short:</strong><br> Kiro AI is still young, but the potential is huge. It could become the “next-gen VS Code”… or just another passing hype.</p><p>Either way, the curiosity alone is reason enough to join the <a href="https://kiro.dev/"><strong>Kiro AI waitlist</strong></a> and try it out once access opens up. 😉</p><blockquote>Kiro AI: More Than Copilot?</blockquote><p><strong>📫 Let’s Connect</strong></p><ul><li>📧 Email: <a href="http://taufik.amary@gmail.com/">taufik.amary@gmail.com</a></li><li>💻 GitHub: <a href="https://github.com/amary21">github.com/amary21</a></li><li>💼 LinkedIn: <a href="http://www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af1c726bc4e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ The Power of Chucker: Debugging Encrypted Endpoints on Android Without Losing QA Evidence]]></title>
            <link>https://taufik-amary.medium.com/the-power-of-chucker-debugging-encrypted-endpoints-on-android-without-losing-qa-evidence-491d91b7c388?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/491d91b7c388</guid>
            <category><![CDATA[mobile-qa]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[chucker]]></category>
            <category><![CDATA[encrypted-api]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 00:41:39 GMT</pubDate>
            <atom:updated>2025-08-08T00:41:39.741Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Frustrated as an Android QA or dev when API responses are encrypted and unreadable in your debugging tool? You’re not alone.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iW4qsIowHzP_asjM" /><figcaption>Photo by <a href="https://unsplash.com/@nublson?utm_source=medium&amp;utm_medium=referral">Nubelson Fernandes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine testing a refund feature in a finance app, and when you try to capture testing evidence, Chucker only displays a string of random characters. Suddenly, your testing process stalls — evidence can’t be validated, results are ambiguous, and communication with developers becomes harder.</p><p>Chucker is a fantastic tool for inspecting HTTP requests and responses directly within your app. QA teams rely on it to validate backend workflows and capture screenshots as evidence for bug reports and feature verification. But when applications encrypt their endpoints for security, Chucker’s usefulness drops: all you see is unreadable gibberish.</p><blockquote><strong>How can QA teams still do their job without compromising security?</strong></blockquote><h3>🧰 What is Chucker and Why Does It Matter?</h3><p><a href="https://github.com/ChuckerTeam/chucker">Chucker</a> is an open-source Android library that surfaces HTTP request and response data directly inside the app UI.</p><p>Unlike tools like <strong>Charles Proxy</strong> or <strong>Postman Interceptor</strong>, Chucker is embedded, making it more convenient for mobile QA and developers. This direct access enables QA engineers to:</p><ul><li>Validate backend flows instantly</li><li>Capture screenshots for documentation</li><li>Avoid additional log statements or external tools</li></ul><h3>🔐 The Challenge: When API Payloads Are Encrypted</h3><p>Apps in finance, insurance, healthcare, or identity verification often <strong>encrypt all API payloads</strong> for security.</p><p>This is great for production, but frustrating for QA. Instead of readable JSON, Chucker displays something like this:</p><pre>j23kj4b23jk4b23jk4b2j34b2j34... (unreadable encrypted blob)</pre><p>Which leads to major issues:</p><ul><li>📎 Evidence screenshots become useless</li><li>❌ QA can’t validate or trace request/response correctness</li><li>🐛 Bug reporting and developer collaboration becomes difficult</li></ul><p>Clearly, we need a way to <strong>decrypt</strong> payloads — but only in debug mode and without weakening security.</p><h3>🛠️ The Solution: Customizing Chucker with a BodyDecoder</h3><p>Chucker supports custom <strong>BodyDecoder</strong>, allowing you to plug in your own decryption logic for requests and responses. This decoder will run only in debug builds and will transform encrypted payloads into readable JSON — just for QA and testing purposes.</p><p>Here’s a simplified example using a fictional AESChipher and static key:</p><pre>// Class body decoder for decrypt request &amp; response<br>class ChuckerBodyDecoder : BodyDecoder {<br><br>    override fun decodeRequest(request: Request, body: ByteString): String? {<br>        return convertByteStringToJson(body)<br>    }<br><br>    override fun decodeResponse(response: Response, body: ByteString): String? {<br>        return convertByteStringToJson(body)<br>    }<br>    <br>    private fun convertByteStringToJson(body: ByteString): String? {<br>        val bodyString = body.string(Charsets.UTF_8)<br>        val decryptedString = AESCipher.decrypt(bodyString, &quot;key&quot;)<br>        return decryptedString // Return the readable, decrypted JSON string<br>    }<br><br>}</pre><p>And to hook it into your Chucker setup:</p><pre>// Implement BodyDecoder into Chucker interceptor<br>val chuckerInterceptor = ChuckerInterceptor.Builder(context)<br>    .addBodyDecoder(ChuckerBodyDecoder())<br>    .build()</pre><p>With this setup, Chucker will automatically decrypt request and response bodies before displaying them in the UI — enabling QA to view full readable payloads during testing.</p><h3>✅ The Result: Decrypted Responses Only in Debug Mode</h3><p>Before applying the custom BodyDecoder, Chucker displays encrypted payloads that are unreadable and useless for QA validation.</p><p>After integrating ChuckerBodyDecoder, the same response becomes a clean, formatted JSON that QA engineers can read and verify.</p><h4>🔒 Before: Encrypted Response in Chucker (No BodyDecoder)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AInq2S_JYfvQhaqn2AzJ8g.png" /></figure><h4>🔓 After: Decrypted Response with BodyDecoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qd_2l75eneL-OuIqZuDlHg.png" /></figure><p>With this improvement, QA engineers can now:</p><ul><li>✅ Validate request and response correctness</li><li>📸 Capture valid screenshots for test evidence</li><li>🤝 Collaborate more effectively with developers</li></ul><h3>🔒 Important Security Notes</h3><p>To keep this approach safe and production-ready:</p><ul><li>🔐 <strong>Do not include decryption logic in release builds</strong></li><li>🛡️ <strong>Protect your keys properly</strong> (e.g., with Android Keystore or secure obfuscation)</li><li>🧪 <strong>Restrict usage to QA/internal builds only</strong></li></ul><p>For example:</p><pre>if (BuildConfig.DEBUG) {<br>    // Only use Chucker Interceptor in debug mode<br>}</pre><h3>🧑‍💻 Best Practices for QA Teams</h3><ul><li>Use decrypted payloads <strong>only for internal testing</strong></li><li>Keep screenshots in <strong>secure, access-controlled storage</strong></li><li>Never expose decrypted content in public channels or documentation</li><li>Collaborate with security teams to maintain compliance</li></ul><h3>📣 Final Thoughts</h3><p>Encrypted APIs shouldn’t block effective QA and debugging.</p><p>By customizing Chucker with a BodyDecoder, teams can enable <strong>secure, readable debugging</strong> in development builds — without compromising production security.</p><blockquote>🔧 It’s a small change that makes a big impact on testing workflows.</blockquote><p>Have you implemented something similar in your project? Or faced challenges when working with encrypted responses?</p><p>Let’s chat in the comments, or connect with me directly for a technical discussion!<br> And if you’re ready to try this, check out <a href="https://github.com/ChuckerTeam/chucker"><strong>Chucker’s GitHub repo</strong></a> and start experimenting.</p><p><strong>Happy debugging!</strong> 🚀🛠️</p><p><strong>📫 Let’s Connect</strong></p><ul><li>📧 Email: <a href="http://taufik.amary@gmail.com/">taufik.amary@gmail.com</a></li><li>💻 GitHub: <a href="https://github.com/amary21">github.com/amary21</a></li><li>💼 LinkedIn: <a href="http://www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491d91b7c388" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Gemini AI Changed My OCR Development Approach]]></title>
            <link>https://taufik-amary.medium.com/why-gemini-ai-changed-my-ocr-development-approach-fe19c6b41d94?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe19c6b41d94</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[indonesia]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 09:07:59 GMT</pubDate>
            <atom:updated>2025-07-27T09:07:59.846Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>From traditional OCR libraries to AI-powered structured data extraction with Kotlin Multiplatform</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMg61kii1PZVQNrH" /><figcaption>Photo by <a href="https://unsplash.com/@cardmapr?utm_source=medium&amp;utm_medium=referral">CardMapr.nl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The OCR Challenge I Faced</h3><p>While working on document processing applications, I was familiar with OCR technologies like OpenCV with Tesseract and Google ML Kit. These are mature, reliable solutions that work well for basic text extraction. However, when building applications that need structured data from Indonesian documents, I consistently ran into the same workflow:</p><ol><li><strong>Extract raw text</strong> with traditional OCR</li><li><strong>Parse and clean</strong> the messy output</li><li><strong>Map fields</strong> to proper data structure</li><li><strong>Handle edge cases</strong> and formatting inconsistencies</li><li><strong>Validate and correct</strong> extracted information</li></ol><p>This multi-step process was not only time-consuming but also error-prone, especially with Indonesian documents that have specific formatting and language nuances.</p><h3>The Gemini AI Discovery</h3><p>During my exploration of cross-platform development with Kotlin Multiplatform, I stumbled upon Google’s Gemini AI and wondered: <em>What if I could skip all the post-processing steps and get structured data directly?</em></p><p>This curiosity led me to experiment with a different approach — using generative AI not just for text recognition, but for intelligent document understanding and structured data extraction.</p><h3>My Kotlin Multiplatform Decision</h3><p>For this experiment, I chose Kotlin Multiplatform because I wanted to test the approach on both Android and iOS without duplicating the complex OCR logic. The benefits were immediate:</p><ul><li><strong>Reduce development time by 60%</strong></li><li><strong>Share complex OCR logic</strong> without code duplication</li><li><strong>Maintain native performance</strong> on both platforms</li></ul><h3>Key Application Features</h3><h4>🎯 Automatic KTP Recognition</h4><ul><li>Camera interface with framing guidance</li><li>Flash control for optimal lighting</li><li>Real-time processing with Gemini AI</li></ul><h4>Comprehensive Data Extraction</h4><p>The application extracts all KTP information according to official format:</p><ul><li><strong>Personal Data</strong>: NIK, Name, Place/Date of birth, Gender</li><li><strong>Complete Address</strong>: Province, Regency/City, Address, RT/RW, Village/Sub-district, District</li><li><strong>Other Information</strong>: Religion, Marital status, Occupation, Citizenship</li></ul><p>Output in structured JSON format ready for use.</p><h3>Implementation with Kotlin Multiplatform</h3><h4>Technology Stack</h4><pre>🚀 Kotlin Multiplatform - Cross-platform code sharing<br>🎨 Compose Multiplatform - Unified UI framework  <br>🤖 Google Gemini AI (gemini-2.5-flash) - OCR processing<br>📡 Ktor Client - API communication<br>🔧 Koin - Dependency injection<br>📷 CameraK - Camera functionality<br>📄 Kotlinx Serialization - JSON parsing</pre><h4>Why Gemini AI?</h4><p>After experimenting with both approaches, Gemini AI offered several advantages over traditional OCR libraries:</p><ul><li><strong>Context understanding</strong> beyond simple text recognition</li><li><strong>Structured output</strong> directly from AI without parsing</li><li><strong>Multimodal capabilities</strong> that handle document layout and formatting</li><li><strong>No complex preprocessing</strong> required for document preparation</li></ul><h4>Project Architecture</h4><pre>📁 MyOCRGemini/<br>├── 📁 composeApp/<br>│   ├── 📁 commonMain/      # Shared logic: OCR, camera, API calls, UI<br>│   ├── 📁 androidMain/     # Android-specific setup (minimal)<br>│   └── 📁 iosMain/         # iOS-specific setup (minimal)<br>└── 📁 iosApp/              # iOS app entry point (Xcode project)</pre><h4>How the Application Works</h4><ol><li><strong>Open camera</strong> with frame guide for KTP</li><li><strong>Capture photo</strong> with quality checks</li><li><strong>Send to Gemini AI</strong> for processing</li><li><strong>Receive structured data</strong> within seconds</li></ol><h4>See It in Action</h4><p>Here’s the complete workflow from document positioning to structured data extraction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0beo-bK082PjtogyF-jH7g.gif" /></figure><p><em>Complete OCR workflow: KTP positioning → camera capture → Gemini AI processing → structured data output</em></p><p>The demo shows the intuitive user experience: users simply position their KTP within the frame guide, capture the photo, and receive clean structured data within seconds. Notice how the application provides clear guidance and delivers professional results without any manual data entry or correction needed.</p><h3>Implementation of Key Features</h3><h4>1. Shared OCR Logic (commonMain)</h4><pre>// Gemini API interface for OCR processing<br>interface GeminiApi {<br>    suspend fun extractInfo(request: String): Result&lt;GeminiResponse&gt;<br><br>    companion object {<br>        private const val MODEL_VERSION = &quot;gemini-2.5-flash&quot;<br>        private const val URL = &quot;v1beta/models/$MODEL_VERSION:generateContent&quot;<br><br>        private suspend fun apiKey(): String {<br>            return Res.readBytes(&quot;files/goog_api_key.txt&quot;).decodeToString()<br>        }<br><br>        fun create() = object : GeminiApi {<br>            override suspend fun extractInfo(request: String): Result&lt;GeminiResponse&gt; {<br>                return runCatching {<br>                    NetworkClient.create<br>                        .post(&quot;${NetworkClient.GeminiBaseUrl}$URL&quot;) {<br>                            setBody(request)<br>                            header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                            header(&quot;X-goog-api-key&quot;, apiKey())<br>                        }<br>                        .body()<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>2. Camera Integration Using Shared Code</h4><p>Thanks to the power of third-party libraries like <a href="https://github.com/Kashif-E/CameraK"><strong>CameraK</strong></a>, the camera functionality is fully handled in shared code without any platform-specific implementation. This means:</p><ul><li><strong>No need to write CameraX or UIKit code manually</strong></li><li><strong>Same camera experience across Android and iOS</strong></li><li><strong>Faster development and easier maintenance</strong></li></ul><p>This abstraction simplifies camera setup and lets me focus more on processing logic and UI.</p><h4>3. Compose Multiplatform UI</h4><pre>@Composable<br>fun CameraScreen() {<br>    // Same UI for Android &amp; iOS<br>    // Only camera implementation differs<br>}</pre><h3>Challenges and Solutions</h3><h4>What Went Smoothly ✅</h4><ul><li>Kotlin Multiplatform significantly accelerated development</li><li>Gemini AI high accuracy for Indonesian KTP</li><li>Compose Multiplatform excellent UI consistency</li></ul><h4>Challenges Faced ⚠️</h4><ul><li><strong>Camera permissions</strong> differ per platform → Solved with expect/actual</li><li><strong>Device capabilities</strong> vary → Handled with feature detection</li><li><strong>API cost optimization</strong> → Implemented image compression</li></ul><h4>Current Limitations 📝</h4><p><strong>Important to note</strong>: This research focuses only on <strong>text recognition</strong> from KTP photos. The application cannot yet verify document authenticity or detect counterfeiting.</p><p>For production implementation, verification of document authenticity becomes a crucial aspect that needs further development — this could be an interesting research direction for future exploration.</p><h3>Setup for Developers</h3><pre># Clone repository<br>git clone https://github.com/amary21/MyOCRGemini<br><br># Add your Gemini API key<br>echo &quot;your-gemini-api-key&quot; &gt; composeApp/src/commonMain/composeResources/files/goog_api_key.txt</pre><h3>▶️ Build &amp; Run</h3><h4>For Android:</h4><pre># Build APK for Android (without installing)<br>./gradlew :composeApp:assembleDebug<br><br># (Optional) Find the APK here:<br># composeApp/build/outputs/apk/debug/composeApp-debug.apk<br><br># To install manually:<br>adb install composeApp/build/outputs/apk/debug/composeApp-debug.apk</pre><h4>For iOS (requires macOS + Xcode + real device):</h4><pre># Open the Xcode project<br>open iosApp/iosApp.xcworkspace<br><br># IMPORTANT: Must run on a real device — camera does not work on simulators<br># Select your iPhone device in Xcode and press Run (Cmd + R)</pre><p>The combination of Kotlin Multiplatform and Google Gemini AI proved highly effective for building cross-platform OCR applications. By sharing complex business logic and leveraging powerful AI, we can create robust solutions with minimal development effort.</p><p>This project is open-source and can serve as a good starting point for anyone wanting to explore OCR with modern technologies.</p><h3>Connect &amp; Contribute</h3><p><strong>GitHub Repository</strong>: [<a href="https://github.com/amary21/MyOCRGemini">https://github.com/amary21/MyOCRGemini</a>]<br><strong>LinkedIn</strong>: [<a href="https://medium.com/www.linkedin.com/in/t-amar">www.linkedin.com/in/t-amar</a>]<br><strong>Inspiration &amp; Reference</strong>:<br>Big thanks to <a href="https://github.com/isfaaghyth/iox-mcp">iox-mcp by @isfaaghyth</a> — this project gave me valuable insights into integrating AI with Kotlin Multiplatform, especially around structured data processing and architectural design for cross-platform apps.</p><p><em>Have you implemented OCR or Kotlin Multiplatform? Share your experience in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe19c6b41d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Mobile Monitoring with KMP and OpenTelemetry]]></title>
            <link>https://taufik-amary.medium.com/level-up-mobile-monitoring-with-kmp-and-opentelemetry-c15bd069d2c4?source=rss-5cb5152083c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c15bd069d2c4</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Taufik Amaryansyah]]></dc:creator>
            <pubDate>Tue, 27 May 2025 02:57:32 GMT</pubDate>
            <atom:updated>2025-05-27T02:57:32.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pkwg-VN3exfRqlSm" /><figcaption>Photo by <a href="https://unsplash.com/@ibrahimboran?utm_source=medium&amp;utm_medium=referral">Ibrahim Boran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Supercharge your cross-platform mobile apps with distributed tracing, real-time metrics, and unified observability — without code duplication.</blockquote><h3>Introduction</h3><p>Modern mobile apps require more than just sleek UI and business logic. Robust observability is crucial for reliability and fast debugging — especially when your app runs on both Android and iOS.</p><p>With <strong>Kotlin Multiplatform (KMP)</strong> and <strong>OpenTelemetry</strong>, you can level up your mobile monitoring: instrument your code once, trace and analyze everywhere, and gain real-time insights into app performance across platforms.</p><p>This article shows how combining KMP and OpenTelemetry lets you build next-generation mobile apps with built-in observability — complete with real implementations for Android and iOS, and dashboard screenshots from Grafana.</p><h3>Why Level Up with KMP and OpenTelemetry?</h3><p>Common mobile monitoring pain points:</p><ul><li>Duplicated instrumentation code for every platform</li><li>Inconsistent monitoring and debugging experiences</li><li>Limited real-time visibility into issues and performance</li></ul><p>KMP and OpenTelemetry solve these by offering:</p><ul><li><strong>Shared monitoring logic:</strong> Write it once, use everywhere (Android/iOS)</li><li><strong>End-to-end request tracing:</strong> Diagnose performance issues quickly</li><li><strong>Consistent, real-time metrics:</strong> Unified monitoring data across platforms</li><li><strong>Adaptive detail:</strong> Tune monitoring for battery, user, and device context</li></ul><p>With this approach, you get more robust apps, a better developer experience, and production-ready observability.</p><h4>Step 1: Define a Shared Monitoring Interface</h4><p>Start by defining a common interface in your KMP shared module:</p><pre>interface OpenTelemetryService {<br>    fun build(httpEndpoint: String, authorization: String, serviceName: String, hostName: String)<br>    fun trace(instrumentationName: String, instrumentationVersion: String)<br>    fun createSpan(<br>        spanName: String,<br>        eventName: String = &quot;&quot;,<br>        attributes: Map&lt;String, String&gt; = emptyMap()<br>    )<br>}</pre><h4>Step 2: Instrument Network Requests in Shared Code</h4><p>With KMP, you can write network tracing logic once for all platforms. Example Ktor plugin:</p><pre>private fun interceptorPlugin(openTelemetryService: OpenTelemetryService) = createClientPlugin(&quot;CustomInterceptors&quot;) {<br>    onRequest { request, _ -&gt;<br>        val urlInfo = request.url.host + request.url.encodedPath<br>        openTelemetryService.createSpan(<br>            spanName = &quot;network-request&quot;,<br>            eventName = &quot;Request to $urlInfo&quot;,<br>            attributes = mapOf(&quot;url&quot; to request.url.toString())<br>        )<br>    }<br>    onResponse {<br>        val urlInfo = it.request.url.host + it.request.url.encodedPath<br>        openTelemetryService.createSpan(<br>            spanName = &quot;network-response&quot;,<br>            eventName = &quot;Response from $urlInfo&quot;,<br>            attributes = mapOf(<br>                &quot;status&quot; to it.status.value.toString()<br>            )<br>        )<br>    }<br>}</pre><h4>Step 3: Platform-Specific OpenTelemetry Implementation</h4><p><strong>Android: Using the OpenTelemetry Java SDK</strong></p><p>Here’s an example implementation for Android, using the official OpenTelemetry Java SDK:</p><pre>class OpenTelemetryServiceImpl : OpenTelemetryService {<br>    private var openTelemetrySdk: OpenTelemetrySdk? = null<br>    private var tracer: Tracer? = null<br><br>    override fun build(httpEndpoint: String, authorization: String, serviceName: String, hostName: String) {<br>        val otelResource = Resource.getDefault().merge(<br>            Resource.create(<br>                Attributes.of(<br>                    ResourceAttributes.SERVICE_NAME, serviceName,<br>                    ResourceAttributes.HOST_NAME, hostName<br>                )<br>            )<br>        )<br><br>        val sdkTracerProvider = SdkTracerProvider.builder()<br>            .addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create()))<br>            .addSpanProcessor(BatchSpanProcessor.builder(<br>                OtlpHttpSpanExporter.builder()<br>                    .setEndpoint(httpEndpoint)<br>                    .addHeader(&quot;Authorization&quot;, authorization)<br>                    .build()).build()<br>            )<br>            .setResource(otelResource)<br>            .build()<br><br>        openTelemetrySdk = OpenTelemetrySdk.builder()<br>            .setTracerProvider(sdkTracerProvider)<br>            .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))<br>            .buildAndRegisterGlobal()<br>    }<br><br>    override fun trace(instrumentationName: String, instrumentationVersion: String) {<br>        if (openTelemetrySdk == null) {<br>            Log.e(&quot;trace&quot;, &quot;OpenTelemetry SDK is not initialized. Call build() first.&quot;)<br>            return<br>        }<br><br>        tracer = openTelemetrySdk?.getTracer(<br>            instrumentationName,<br>            instrumentationVersion<br>        )<br>    }<br><br>    override fun createSpan(<br>        spanName: String,<br>        eventName: String,<br>        attributes: Map&lt;String, String&gt;<br>    ) {<br>        if (tracer == null) {<br>            Log.e(&quot;createSpan&quot;, &quot;Tracer is not initialized. Call trace() first.&quot;)<br>            return<br>        }<br>        val span = tracer?.spanBuilder(spanName)?.startSpan()<br>        try {<br>            attributes.forEach { (key, value) -&gt;<br>                span?.setAttribute(key, value)<br>            }<br>            span?.addEvent(eventName)<br>        } catch (t: Throwable) {<br>            span?.setStatus(StatusCode.ERROR, &quot;Error in span: ${t.message}&quot;)<br>            Log.e(&quot;createSpan&quot;, &quot;Error in span: $spanName&quot;, t)<br>        } finally {<br>            span?.end()<br>        }<br>    }<br>}</pre><p><strong>iOS: Using the OpenTelemetry Swift SDK (CocoaPods)</strong></p><p>Add OpenTelemetry as CocoaPods dependencies in your shared module config:</p><pre>cocoapods {<br>    ...<br><br>    pod(&quot;OpenTelemetry-Swift-Sdk&quot;) { <br>        moduleName = &quot;OpenTelemetrySdk&quot;<br>        extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;) <br>    }<br>    pod(&quot;OpenTelemetry-Swift-Api&quot;) { <br>        moduleName = &quot;OpenTelemetryApi&quot; <br>        extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;)<br>    }<br>    pod(&quot;OpenTelemetry-Swift-Protocol-Exporter-Common&quot;) {<br>        moduleName = &quot;OpenTelemetryProtocolExporterCommon&quot;<br>        extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;)<br>    }<br>    pod(&quot;OpenTelemetry-Swift-Protocol-Exporter-Http&quot;) { <br>        moduleName = &quot;OpenTelemetryProtocolExporterHttp&quot; <br>        extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;)<br>    }<br>    pod(&quot;OpenTelemetry-Swift-StdoutExporter&quot;) { <br>        moduleName = &quot;StdoutExporter&quot; <br>        extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;)<br>    }<br><br>    ...<br>}</pre><p>Bridge your KMP interface to the Swift implementation:</p><pre>class OpenTelemetryServiceImpl: OpenTelemetryService {<br>    private var tracer: Tracer? = nil<br><br>    func build(httpEndpoint: String, authorization: String, serviceName: String, hostName: String) {<br>        let url = URL(string: httpEndpoint)<br>        let config = OtlpConfiguration(headers: [(&quot;Authorization&quot;, authorization)])<br>        let otlpHttpTraceExporter = OtlpHttpTraceExporter(endpoint: url!, config: config)<br>        let resource = Resource(attributes: [<br>            ResourceAttributes.serviceName.rawValue: AttributeValue.string(serviceName),<br>            ResourceAttributes.hostName.rawValue: AttributeValue.string(hostName)<br>        ])<br>        let consoleTraceExporter = StdoutSpanExporter(isDebug: true)<br>        OpenTelemetry.registerTracerProvider(<br>            tracerProvider: TracerProviderBuilder()<br>                .add(spanProcessor: BatchSpanProcessor(spanExporter: otlpHttpTraceExporter))<br>                .add(spanProcessor: BatchSpanProcessor(spanExporter: consoleTraceExporter))<br>                .with(resource: resource)<br>                .build()<br>        )<br>    }<br><br>    func trace(instrumentationName: String, instrumentationVersion: String) {<br>        tracer = OpenTelemetry.instance.tracerProvider.get(<br>            instrumentationName: instrumentationName,<br>            instrumentationVersion: instrumentationVersion<br>        )<br>    }<br><br>    func createSpan(spanName: String, eventName: String, attributes: [String: String] = [:]) {<br>        guard let tracer = tracer else {<br>            print(&quot;Tracer is not initialized. Call trace() first.&quot;)<br>            return<br>        }<br>        let span = tracer.spanBuilder(spanName: spanName).startSpan()<br>        attributes.forEach { (key, value) in<br>            span.setAttribute(key: key, value: value)<br>        }<br>        span.addEvent(name: eventName)<br>        span.end()<br>    }<br>}</pre><h4>UI Example: Instrumenting User Actions with Compose Multiplatform</h4><p>With Compose Multiplatform, you can write your UI once and add tracing for user interactions:</p><pre>@Composable<br>fun CharacterItem(character: Character, openTelemetryService: OpenTelemetryService) {<br>    Card(<br>        modifier = Modifier.clickable {<br>            openTelemetryService.createSpan(<br>                &quot;character_item_click&quot;, &quot;Clicked&quot;, mapOf(&quot;character&quot; to character.name)<br>            )<br>        }<br>    ) {<br>        // UI content here<br>    }<br>}</pre><h3>Monitoring Results: From Code to Dashboard</h3><p>Once OpenTelemetry is implemented, observability moves from simple logs to real-time, actionable dashboards.</p><h4>📊 Unified Monitoring in Grafana</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hLy0EXjYwX-jKfmTOW1LQ.png" /></figure><p>All tracing data and API call durations are visualized in a unified Grafana dashboard. Below is a sample from the Mobile Disney service, showing trace logs and API call duration trends:</p><p><em>The top table lists recent network traces with Trace IDs, Span IDs, timestamps, and durations, making it easy to identify latency and trace details. The chart below visualizes API call durations over time, so you can spot spikes or trends instantly. Each point represents an API request, letting you monitor real user experience in real time.</em></p><p>With this observability stack, you turn every mobile event into actionable insight for engineering, QA, and operations.</p><h3>Why This Approach Levels Up Your Workflow</h3><ul><li>🚀 <strong>Faster Debugging:</strong> Instantly trace issues across Android and iOS</li><li>🎯 <strong>Unified Insights:</strong> Consistent metrics, logs, and traces for all platforms</li><li>📉 <strong>Reduced Technical Debt:</strong> Maintain monitoring code in one place</li><li>💡 <strong>Developer Happiness:</strong> More time for features, less time fighting boilerplate</li></ul><h3>Tips &amp; Next-Level Ideas</h3><ul><li><strong>Batch and retry spans</strong> to handle offline/mobile connectivity</li><li><strong>Adjust telemetry detail</strong> for battery/data use and user privacy</li><li><strong>Integrate business KPIs</strong>, not just technical metrics</li><li><strong>Connect with error/crash reporting</strong> for 360° observability</li></ul><h3>Conclusion</h3><p>Kotlin Multiplatform and OpenTelemetry empower you to truly <em>level up</em> your mobile monitoring:</p><blockquote>One codebase, two platforms, and real-time, production-grade observability. Say goodbye to duplicated effort and fragmented insights — unlock reliable, maintainable, and insightful mobile apps.</blockquote><p>Ready to level up your mobile monitoring? Try this stack in your next project and see the difference.</p><h3>Collaboration &amp; References</h3><p>The backend infrastructure — Prometheus, Grafana, Tempo, and related services — was provisioned in partnership with <a href="https://medium.com/@martinuz.dawan9">Martinuz Dawan</a>, whose expertise ensured seamless connectivity and data flow from mobile app to dashboard.</p><h4>Learn More &amp; Official References</h4><ul><li><strong>Backend Observability Stack: </strong><a href="https://medium.com/@martinuz.dawan9/bagian-1-setup-observability-stack-dengan-docker-portainer-01ff21d76396">Bagian 1: Setup Observability Stack dengan Docker &amp; Portainer</a> <em>(in Indonesian, by Martinuz Dawan)</em></li><li><strong>OpenTelemetry for iOS (Swift):</strong> <a href="https://www.alibabacloud.com/help/en/opentelemetry/user-guide/use-opentelemetry-to-submit-trace-data-of-swift-applications">Use OpenTelemetry to Submit Trace Data of Swift Applications</a> <em>(Official Alibaba Cloud Guide)</em></li><li><strong>OpenTelemetry for Android: </strong><a href="https://www.alibabacloud.com/help/en/opentelemetry/user-guide/use-managed-service-for-opentelemetry-to-report-the-trace-data-of-android-applications">Use Managed Service for OpenTelemetry to Report the Trace Data of Android Applications</a> <em>(Official Alibaba Cloud Guide)</em></li><li><strong>GitHub Project (Full Source Code): </strong><a href="https://github.com/amary21/kmp-disney-otel">amary21/kmp-disney-otel</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c15bd069d2c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>