<?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 Meet Miyani on Medium]]></title>
        <description><![CDATA[Stories by Meet Miyani on Medium]]></description>
        <link>https://medium.com/@meet-miyani?source=rss-8f91a9c1967f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zps9ABNbG-5XdcKGpM8teg.jpeg</url>
            <title>Stories by Meet Miyani on Medium</title>
            <link>https://medium.com/@meet-miyani?source=rss-8f91a9c1967f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:22:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meet-miyani/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[How to Add AdMob to a Compose Multiplatform App on Android and iOS]]></title>
            <link>https://meet-miyani.medium.com/admob-compose-multiplatform-android-ios-guide-a46a8be696a7?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a46a8be696a7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[admob]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 05:05:31 GMT</pubDate>
            <atom:updated>2026-08-13T05:05:31.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="AdMob CMP banner showing Compose Multiplatform, Kotlin, the Maven coordinate, and six supported ad formats for Android and iOS." src="https://cdn-images-1.medium.com/max/1024/1*FjqnaKvpWm1GdFhiSOdJcw.png" /><figcaption>AdMob CMP provides one shared Kotlin API over native Google Mobile Ads SDKs on Android and iOS.</figcaption></figure><p><em>A practical Kotlin Multiplatform guide to project setup, UMP consent, App Tracking Transparency, banner ads, interstitials, and safe test configuration.</em></p><p>To add Google AdMob to a Compose Multiplatform app, configure the native Android and iOS hosts, initialize one consent-aware manager from commonMain, and describe each ad placement with Android and iOS unit IDs. The shared Kotlin code can then render banners and control full-screen ads on both platforms.</p><p>This guide uses <a href="https://github.com/Meet-Miyani/admob-compose-multiplatform">AdMob CMP</a>, an open-source SDK that wraps Google Mobile Ads behind one Kotlin Multiplatform API. We will render a safe test banner and prepare an interstitial without building separate expect/actual ad managers.</p><p>The examples use AdMob CMP 2.0.0.</p><p>Before you begin, check the compatibility line for the version you plan to use. Version 2.0.0 is built with Kotlin 2.3.20 and Compose Multiplatform 1.11.1; it targets Android API 26 or newer and iOS 15 or newer.</p><h3>What we are going to build</h3><p>By the end, the shared module will own:</p><ul><li>one process-wide AdManager</li><li>consent-aware initialization</li><li>a banner placement rendered with BannerAdView</li><li>an interstitial controller using suspending load() and show() calls</li><li>Google’s official Android and iOS test ad units</li></ul><p>The native applications will still own the platform configuration Google requires: Android manifest metadata, iOS Swift packages, and Info.plist values.</p><h3>1. Add AdMob CMP to commonMain</h3><p>Add the facade dependency to the shared module:</p><pre>// shared/build.gradle.kts<br>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(&quot;dev.avinya.ads:admob-cmp:2.0.0&quot;)<br>        }<br>    }<br>}</pre><p>Make sure the build resolves both Google’s and Maven Central’s repositories:</p><pre>// settings.gradle.kts<br>pluginManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>        gradlePluginPortal()<br>    }<br>}<br><br>dependencyResolutionManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>}</pre><p>If the shared module runs Kotlin/Native tests such as iosSimulatorArm64Test, also apply the AdMob CMP Gradle plugin:</p><pre>// shared/build.gradle.kts<br>plugins {<br>    id(&quot;dev.avinya.ads.admob-cmp&quot;) version &quot;2.0.0&quot;<br>}</pre><p>The plugin supplies the matching Google Mobile Ads and UMP frameworks to Kotlin/Native test executables. It does not replace Swift Package Manager in the production iOS app.</p><h3>2. Configure the Android application</h3><p>Google Mobile Ads requires an application ID in the runnable Android application module. Add the metadata inside the &lt;application&gt; element:</p><pre>&lt;!-- androidApp/src/main/AndroidManifest.xml --&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;application&gt;<br>        &lt;meta-data<br>            android:name=&quot;com.google.android.gms.ads.APPLICATION_ID&quot;<br>            android:value=&quot;ca-app-pub-3940256099942544~3347511713&quot; /&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>That is Google’s sample Android app ID. Replace it with the real app ID before release.</p><p>An app ID contains a tilde (~). An ad-unit ID contains a slash (/). Mixing them is a common setup mistake.</p><h3>3. Configure the iOS application</h3><p>AdMob CMP publishes Kotlin/Native bindings, but Google’s iOS binaries remain native dependencies of the host application.</p><p>In Xcode, choose File → Add Package Dependencies and add:</p><ul><li>https://github.com/googleads/swift-package-manager-google-mobile-ads.git using the compatible 13.x line</li><li>https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git using the compatible 3.x line</li></ul><p>Select the GoogleMobileAds and GoogleUserMessagingPlatform products for the iOS app target.</p><p>Then add the sample application ID and the ATT usage description to Info.plist:</p><pre>&lt;key&gt;GADApplicationIdentifier&lt;/key&gt;<br>&lt;string&gt;ca-app-pub-3940256099942544~1458002511&lt;/string&gt;<br><br>&lt;key&gt;NSUserTrackingUsageDescription&lt;/key&gt;<br>&lt;string&gt;This identifier is used to deliver personalised ads to you.&lt;/string&gt;</pre><p>Before release, replace the sample app ID, add Google’s current SKAdNetworkItems, and review the App Store privacy disclosure. The full <a href="https://ads.avinya.dev/start/ios-setup/">iOS setup guide</a> keeps those native requirements in one place.</p><p>If a static Kotlin framework later fails with _OBJC_CLASS_$_JSContext, add this to the app target’s Other Linker Flags:</p><pre>$(inherited) -framework JavaScriptCore</pre><h3>4. Initialize AdMob after UMP consent and iOS ATT</h3><p>Call rememberAdManager() once near the root of the shared Compose application. Provide that same manager to the rest of the tree through LocalAdManager.</p><p>For iOS, the production order is UMP consent, then App Tracking Transparency, then Google Mobile Ads initialization. An initialization hook places the ATT request between consent and native SDK startup. On Android, the tracking controller is a no-op.</p><pre>@Composable<br>fun App() {<br>    val adManager = rememberAdManager()<br><br>    LaunchedEffect(adManager) {<br>        val config = AdConfig(<br>            androidAppId = TestAdIds.ANDROID_APP_ID,<br>            iosAppId = TestAdIds.IOS_APP_ID,<br>            initializationHooks = listOf(<br>                object : AdInitializationHook {<br>                    override suspend fun onPhase(<br>                        phase: AdInitializationPhase,<br>                        config: AdConfig,<br>                    ) {<br>                        if (phase == AdInitializationPhase.BeforeMobileAdsInitialize) {<br>                            adManager.tracking.requestAuthorization()<br>                        }<br>                    }<br>                }<br>            ),<br>        )<br><br>        adManager.gatherConsentAndInitialize(config)<br>    }<br><br>    val status by adManager.status.collectAsState()<br><br>    if (status is AdManagerStatus.Ready) {<br>        CompositionLocalProvider(LocalAdManager provides adManager) {<br>            MainAdScreen(adManager)<br>        }<br>    } else {<br>        Box(<br>            modifier = Modifier.fillMaxSize(),<br>            contentAlignment = Alignment.Center,<br>        ) {<br>            CircularProgressIndicator()<br>        }<br>    }<br>}</pre><p>gatherConsentAndInitialize() requests a UMP update, shows the consent form when required, and initializes ads only when requests are allowed. The hook handles the separate iOS ATT step before native initialization.</p><p>Do not request ads merely because the app has entered composition. Gate ad-dependent UI on AdManagerStatus.Ready.</p><h3>5. Render a banner from commonMain</h3><p>Create one stable placement. A placement gives the logical location a finite ID and resolves the correct ad-unit ID for each platform.</p><pre>@Composable<br>fun MainAdScreen(adManager: AdManager) {<br>    val bannerPlacement = remember {<br>        AdPlacement(<br>            id = &quot;home_banner&quot;,<br>            format = AdFormat.Banner,<br>            androidAdUnitId = TestAdIds.ANDROID_BANNER,<br>            iosAdUnitId = TestAdIds.IOS_BANNER,<br>            strictTestMode = true,<br>        )<br>    }<br><br>    Column {<br>        Text(&quot;My Compose Multiplatform app&quot;)<br><br>        BannerAdView(<br>            placement = bannerPlacement,<br>            modifier = Modifier.fillMaxWidth(),<br>            onEvent = { event -&gt;<br>                when (event) {<br>                    is AdEvent.Loaded -&gt; println(&quot;Banner loaded&quot;)<br>                    is AdEvent.LoadFailed -&gt; println(&quot;Banner failed: ${event.error}&quot;)<br>                    else -&gt; Unit<br>                }<br>            },<br>        )<br><br>        InterstitialButton(adManager)<br>    }<br>}</pre><p>BannerAdView measures its Compose container and passes the width to the platform banner controller. That matters for adaptive banners on resizable layouts, including iPad split view and Slide Over.</p><p>Keep placement IDs static and finite. Do not create IDs such as &quot;banner_${item.id}&quot; for an unbounded list; the manager caches controllers by placement ID for its lifetime.</p><h3>6. Load and show an interstitial</h3><p>Full-screen formats use controllers rather than composables. Create the controller with remember, preload the ad before the natural break where it may be shown, and call show() from a UI-scoped coroutine.</p><pre>@Composable<br>fun InterstitialButton(adManager: AdManager) {<br>    val placement = remember {<br>        AdPlacement(<br>            id = &quot;article_complete&quot;,<br>            format = AdFormat.Interstitial,<br>            androidAdUnitId = TestAdIds.ANDROID_INTERSTITIAL,<br>            iosAdUnitId = TestAdIds.IOS_INTERSTITIAL,<br>            strictTestMode = true,<br>        )<br>    }<br><br>    val interstitial = remember(adManager) {<br>        adManager.interstitial(placement)<br>    }<br>    val scope = rememberCoroutineScope()<br><br>    LaunchedEffect(interstitial) {<br>        interstitial.load()<br>    }<br><br>    Button(<br>        onClick = {<br>            scope.launch {<br>                when (val result = interstitial.show()) {<br>                    is AdShowResult.Shown -&gt; {<br>                        // The ad was shown and has now been dismissed.<br>                    }<br>                    is AdShowResult.NotReady -&gt; {<br>                        // Nothing was ready. Continue without blocking the user.<br>                    }<br>                    is AdShowResult.Failed -&gt; {<br>                        println(&quot;Show failed: ${result.error}&quot;)<br>                    }<br>                }<br>            }<br>        },<br>    ) {<br>        Text(&quot;Continue&quot;)<br>    }<br>}</pre><p>show() suspends until the ad is dismissed. Do not launch it in GlobalScope, and do not assume that returning from the call always means the ad was shown. Branch on AdShowResult.</p><p>Also avoid loading at the exact moment the user taps Continue. Preload earlier, then treat NotReady as a normal path that should not trap the user behind an ad request.</p><h3>7. Use test ads without risking live traffic</h3><p>The safest development setup uses Google’s official sample IDs through TestAdIds and sets strictTestMode = true on every test placement.</p><p>The two similarly named flags serve different purposes:</p><ul><li>AdConfig.testMode enables UMP consent debugging. It does not make Google Mobile Ads return test ads.</li><li>AdPlacement.strictTestMode rejects production ad-unit IDs at construction. Use it in development builds with TestAdIds.</li></ul><p>For QA against your own production ad units, register the physical device’s hashed test ID in GlobalRequestConfiguration.testDeviceIds instead. Emulators and simulators are automatically treated as test devices.</p><p>Never click live ads during development. A debug flag that only changes consent behavior is not protection against invalid traffic.</p><h3>8. Add the other AdMob formats</h3><p>The same shared manager exposes all six Android and iOS formats:</p><ul><li>BannerAdView(placement) for banners, including adaptive and collapsible policies</li><li>adManager.interstitial(placement) for interstitials</li><li>adManager.rewarded(placement) for rewarded ads</li><li>adManager.rewardedInterstitial(placement) for rewarded interstitials</li><li>adManager.appOpen(placement) with AppOpenAdCoordinator</li><li>NativeAdView with a bounded native-ad session and declarative layout DSL</li></ul><p>Rewarded and app-open formats have extra product rules, while native ads need stable logical slot keys and session ownership. Start with the dedicated <a href="https://ads.avinya.dev/formats/banner/">format guides</a> instead of copying a banner lifecycle into every format.</p><h3>Production checklist</h3><p>Before replacing the sample IDs, verify each of these deliberately:</p><ol><li>Use real AdMob app IDs in the Android manifest and iOS Info.plist.</li><li>Use real Android and iOS ad-unit IDs in every production placement.</li><li>Disable UMP debug geography and consent test devices.</li><li>Set strictTestMode = false only in the production configuration.</li><li>Keep UMP consent before ATT and ATT before the first iOS ad request.</li><li>Show privacy settings only when privacyOptionsRequirementStatus is Required.</li><li>Complete Google Play Data Safety and App Store privacy disclosures for the app’s actual configuration.</li><li>Test on real Android and iOS devices, including denied consent, denied ATT, no-fill, offline, background, and foreground paths.</li></ol><p>For iOS diagnostics, run:</p><pre>./gradlew :shared:doctorIos<br>./gradlew :shared:iosSimulatorArm64Test</pre><p>The first command reports configuration problems. The second proves that the consumer’s Kotlin/Native test executable can link the Google frameworks.</p><h3>Common questions</h3><h4>Does Google AdMob have an official Kotlin Multiplatform SDK?</h4><p>Google publishes native Mobile Ads SDKs for <a href="https://developers.google.com/admob/android/next-gen/quick-start">Android</a> and <a href="https://developers.google.com/admob/ios/quick-start">iOS</a>, not a shared Kotlin Multiplatform API. AdMob CMP binds those native SDKs behind a common Kotlin contract; the host applications still complete Google’s required native configuration.</p><h4>Can I integrate AdMob with expect/actual instead?</h4><p>Yes. A small expect/actual bridge can be appropriate for one simple banner. The maintenance cost grows when the app adds full-screen formats, consent, ATT, caching, native-ad ownership, shared events, or Kotlin/Native tests. At that point, the bridge is becoming an application-specific ad SDK.</p><h4>Where should ad placements live?</h4><p>Use stable, finite, product-level IDs such as home_banner or article_complete. Keep them in shared configuration or provide them through LocalAdPlacements. Do not generate a new placement ID for each feed row or navigation instance.</p><h4>Does AdMob CMP support desktop and web ads?</h4><p>No. The advertising implementation targets Android and iOS. A larger Compose Multiplatform application can keep desktop and web targets ad-free while sharing the rest of its UI and business logic.</p><h3>Where to go next</h3><p>The complete <a href="https://ads.avinya.dev/start/quickstart/">AdMob CMP quickstart</a> is the shortest path from an empty project to a rendered test ad. The documentation also covers <a href="https://ads.avinya.dev/privacy/consent/">consent</a>, <a href="https://ads.avinya.dev/privacy/app-tracking-transparency/">App Tracking Transparency</a>, <a href="https://ads.avinya.dev/formats/native/">native ads</a>, caching, revenue events, mediation, and troubleshooting.</p><p>You can inspect the implementation, run the showcase app, report edge cases, or star the project on <a href="https://github.com/Meet-Miyani/admob-compose-multiplatform">GitHub</a>.</p><p>If you are interested in why I built the SDK instead of maintaining another pair of expect/actual ad managers, read the first article in this series: <a href="https://meet-miyani.medium.com/why-i-built-admob-cmp-compose-multiplatform-146fed8cc4ec?sharedUserId=meet-miyani">I Couldn’t Find a Clean Way to Add AdMob to Compose Multiplatform, So I Built One.</a></p><p><em>AdMob CMP is an independent open-source project. It is not affiliated with or endorsed by Google. AdMob and Google Mobile Ads are trademarks of Google LLC.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a46a8be696a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Couldn’t Find a Clean Way to Add AdMob to Compose Multiplatform, So I Built One]]></title>
            <link>https://meet-miyani.medium.com/why-i-built-admob-cmp-compose-multiplatform-146fed8cc4ec?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/146fed8cc4ec</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[admob]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 04:26:09 GMT</pubDate>
            <atom:updated>2026-08-13T05:06:55.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="AdMob CMP banner showing Compose Multiplatform, Kotlin, the Maven coordinate, and six supported ad formats for Android and iOS." src="https://cdn-images-1.medium.com/max/1024/1*FjqnaKvpWm1GdFhiSOdJcw.png" /></figure><p><em>The path from a working banner to a production-grade Kotlin Multiplatform ad layer, and why I stopped duplicating state, callbacks, and lifecycle code.</em></p><p>When I started looking for a clean way to add AdMob to a Compose Multiplatform app, I found plenty of examples that could display a banner. What I could not find was a solution I would trust with the full life of a production app: Android and iOS, consent, full-screen ads, native feeds, retries, caching, and testing.</p><p>The usual answer was reasonable: create an expect declaration in commonMain, write an actual implementation for Android, write another for iOS, and bridge the native views into Compose.</p><p>That approach works. For one banner, it may even be the right approach.</p><p>But a working demo and a maintainable advertising layer are two different things.</p><h3>The first banner was not the real problem</h3><p>A basic Kotlin Multiplatform AdMob integration often begins like this:</p><pre>// commonMain<br>@Composable<br>expect fun AdMobBanner(modifier: Modifier = Modifier)</pre><p>Then Android renders an AdView, iOS renders a GADBannerView, and both are exposed through one shared composable.</p><p>The result feels like success because an ad appears on both screens. I had crossed the platform boundary and kept my shared UI clean.</p><p>Then the requirements grew.</p><p>I needed interstitial and rewarded ads. I needed to know when an ad had loaded, failed, opened, closed, earned revenue, or granted a reward. I needed cached ads to expire instead of being shown hours later. I needed app-open ads to stay away from onboarding and other full-screen flows.</p><p>The small bridge started becoming an ad framework hidden inside the application.</p><p>Every new behavior had two implementations, two callback models, two threading rules, and two opportunities to disagree.</p><p>That was the point where I stopped asking, “Can expect/actual make this compile?&quot; and started asking, &quot;Who owns this ad, and what happens to it when the UI disappears?&quot;</p><h3>Ads are mostly an ownership problem</h3><p>The difficult part of mobile ads is rarely the load() call. It is everything around that call.</p><p>What happens if a coroutine is cancelled while a full-screen ad is still visible? Can another ad be presented at the same time? If a banner refresh fails, should the current banner disappear? If a feed row leaves a LazyColumn, is its native ad still reusable? What happens when a user leaves a tab and comes back?</p><p>Compose makes UI lifetime explicit. Native ad SDKs bring their own object lifetime. Those lifetimes do not automatically agree.</p><p>Native ads made this especially clear. A stable item key can identify a row, but it does not preserve the platform ad object behind that row. A composable may leave composition while the logical feed still exists. If the app owns the native object directly, it can reload too often, leak it, reuse it incorrectly, or lose it during ordinary navigation.</p><p>I learned a simple rule from that work:</p><blockquote><em>A stable key preserves identity. It does not create ownership.</em></blockquote><p>That distinction eventually led me away from a loose pool of native ads and toward bounded, session-based ownership. The feed reports stable logical slots. The SDK owns loaded platform objects. The composable receives a short-lived render lease only while it is on screen.</p><p>That is more machinery than a tutorial banner needs. It is also the kind of machinery a real feed quietly demands.</p><h3>Privacy could not remain an afterthought</h3><p>The next problem was initialization.</p><p>It is easy to call Google Mobile Ads as soon as the app launches. A production flow needs more care. UMP consent must be resolved before ad requests are allowed. On iOS, App Tracking Transparency has its own system prompt and timing. The application also needs a privacy-options entry point when UMP requires one.</p><p>The order matters:</p><ol><li>Gather or refresh UMP consent.</li><li>Request ATT authorization on iOS when appropriate.</li><li>Initialize Google Mobile Ads.</li><li>Request ads only when the manager is ready and consent permits them.</li></ol><p>When this logic lives independently in two platform entry points, small differences are easy to introduce and hard to notice. I wanted consent state to be part of the ad API, not a paragraph developers were expected to remember after copying the initialization snippet.</p><h3>iOS worked until the tests had to link</h3><p>There was another sharp edge that only appeared after the application itself was running.</p><p>Xcode can resolve Google Mobile Ads through Swift Package Manager when it builds the iOS app. A Kotlin/Native test executable is linked by Gradle, outside that Xcode build. The bindings compile, but the test linker cannot find symbols such as _OBJC_CLASS_$_GADBannerView unless the native frameworks are supplied separately.</p><p>The manual workaround is possible: download matching XCFrameworks, verify them, cache them, and apply the correct linker flags to test binaries without changing the production framework.</p><p>It is also exactly the kind of build logic every application should not have to maintain.</p><p>That became a Gradle plugin in AdMob CMP. The consumer applies one plugin when it runs Kotlin/Native tests, while the shipped iOS application continues to link Google’s SDKs through Swift Package Manager.</p><p>The lesson was broader than that linker error:</p><blockquote><em>Cross-platform code is not finished when both apps launch. It is finished when both platforms can also be tested, diagnosed, and upgraded without folklore.</em></blockquote><h3>Building the shared layer</h3><p>I eventually built <a href="https://github.com/Meet-Miyani/admob-compose-multiplatform">AdMob CMP</a>, an open-source Compose Multiplatform AdMob SDK for Android and iOS.</p><p>The project now has three deliberate layers:</p><ul><li>A Compose-free core containing consent, placements, state machines, caching, retries, full-screen presentation ownership, and native-ad sessions.</li><li>A Compose layer containing rememberAdManager(), BannerAdView, NativeAdView, and the native-ad layout DSL.</li><li>A single facade artifact (dev.avinya.ads:admob-cmp) so most applications only need one dependency.</li></ul><p>The API stays in commonMain, but it does not pretend the platforms are identical. Android uses Google Mobile Ads Next-Gen. iOS uses Google Mobile Ads through Kotlin/Native cinterop and native framework linking. Platform differences stay behind the boundary while shared concepts remain shared.</p><p>Here is the shape I wanted at the beginning:</p><pre>val adManager = rememberAdManager()<br><br>val placement = remember {<br>    AdPlacement(<br>        id = &quot;main_interstitial&quot;,<br>        format = AdFormat.Interstitial,<br>        androidAdUnitId = TestAdIds.ANDROID_INTERSTITIAL,<br>        iosAdUnitId = TestAdIds.IOS_INTERSTITIAL,<br>        strictTestMode = true,<br>    )<br>}<br><br>val interstitial = remember(adManager) {<br>    adManager.interstitial(placement)<br>}<br><br>scope.launch {<br>    interstitial.load()<br><br>    when (val result = interstitial.show()) {<br>        is AdShowResult.Shown -&gt; Unit<br>        is AdShowResult.NotReady -&gt; Unit<br>        is AdShowResult.Failed -&gt; log(result.error)<br>    }<br>}</pre><p>The same controller model covers interstitial, rewarded, rewarded-interstitial, and app-open ads. Banners and native ads get Compose-native rendering APIs. State is exposed through StateFlow; events arrive through a shared event model; show() suspends until the ad is dismissed.</p><p>Today the SDK supports six formats on Android and iOS: banner, interstitial, rewarded, rewarded interstitial, app-open, and native.</p><h3>What the SDK deliberately does not hide</h3><p>A clean abstraction should remove repeated machinery, not erase important platform responsibilities.</p><p>Applications still provide their own AdMob app IDs and ad-unit IDs. Android still needs its manifest metadata. iOS still links Google Mobile Ads and UMP through Swift Package Manager and supplies the required Info.plist values. Store disclosures, consent policy, mediation adapters, and decisions about where ads belong remain the application&#39;s responsibility.</p><p>AdMob CMP also does not make ads appear on desktop or web. The ad-capable surface targets Android and iOS, while a broader Compose Multiplatform application can keep its unsupported targets ad-free.</p><p>That boundary matters to me. “Cross-platform” should not mean pretending every platform has the same SDK. It should mean giving the shared application one dependable contract around the differences that actually exist.</p><h3>Could I have stayed with expect/actual?</h3><p>Yes.</p><p>If an app needs one banner, rarely changes it, and does not need a shared lifecycle model, a small local bridge may be the simplest answer. I would not add a large abstraction merely to avoid two short files.</p><p>The calculation changes when the application needs several formats, privacy flow, shared telemetry, native feeds, cache policy, reliable full-screen ownership, or Kotlin/Native tests. At that point, the hand-written bridge is no longer just integration code. It is an SDK maintained inside one app.</p><h3>Try it in a Compose Multiplatform app</h3><p>I built AdMob CMP for that point.</p><p>If you want to render a test ad first, start with the <a href="https://ads.avinya.dev/start/quickstart/">five-minute quickstart</a>. It covers the dependency, Android and iOS app IDs, consent-aware initialization, and a shared banner placement.</p><p>The complete source is on <a href="https://github.com/Meet-Miyani/admob-compose-multiplatform">GitHub</a>. If the project solves a problem you have also run into, a star helps other Kotlin Multiplatform developers discover it. Issues and discussions are welcome too, especially the awkward platform cases that simple examples usually leave out.</p><p>In the <a href="https://meet-miyani.medium.com/admob-compose-multiplatform-android-ios-guide-a46a8be696a7?sharedUserId=meet-miyani">next article</a>, I will walk through the implementation step by step: project setup, UMP and ATT ordering, a shared banner, an interstitial, test safety, and the final production checklist.</p><p><em>AdMob CMP is an independent open-source project. It is not affiliated with or endorsed by Google. AdMob and Google Mobile Ads are trademarks of Google LLC.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146fed8cc4ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Shipping Broken AI Agent Skills: Try the Free Online Skill Validator]]></title>
            <link>https://meet-miyani.medium.com/stop-shipping-broken-ai-agent-skills-try-the-free-online-skill-validator-077c973fa9bc?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/077c973fa9bc</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[agent-skills]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-skills]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Fri, 15 May 2026 08:25:51 GMT</pubDate>
            <atom:updated>2026-05-15T08:25:51.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJw9SEW-Z___IkbtKx2r3w.png" /></figure><p>How to optimize LLM token usage, fix markdown references, and secure your agentic workflows with SkillLint — no installation required.</p><p>We are officially in the era of <strong>agentic workflows</strong>. Whether you are building custom AI agents, configuring Cursor rules, or developing specialized toolsets for Large Language Models (LLMs), developers are writing “skills” faster than ever.</p><p>These AI skills empower language models to read your codebase, execute terminal commands, and orchestrate complex tasks autonomously.</p><p>But there’s a massive, hidden problem slowing down AI development.</p><p><strong>Agent skills are incredibly easy to write, but dangerously easy to ship with invisible flaws.</strong></p><h3>Why Do AI Agent Skills Fail?</h3><p>When an AI agent hallucinates or fails a task, we are quick to blame the LLM. But more often than not, the fault lies in the tools we provided. A poorly structured SKILL.md can cripple even the smartest models like GPT-4o or Claude 3.5 Sonnet.</p><p>Here are the silent killers of AI agent performance:</p><ul><li><strong>Vague Trigger Descriptions:</strong> Using generic verbs confuses the LLM on <em>when</em> to actually use the skill, leading to skipped instructions.</li><li><strong>Bloated Context Windows:</strong> Sending massive, unoptimized reference files eats up your expensive token budget and degrades the AI’s reasoning capabilities.</li><li><strong>Broken Markdown Links:</strong> Orphaned references and missing files lead to immediate tool execution errors.</li><li><strong>Security Vulnerabilities:</strong> Credentials, API keys, or dangerous shell command patterns accidentally bundled within helper scripts.</li></ul><p>To solve this, we need the equivalent of ESLint — but designed specifically for AI agent tools. That is exactly why I built <strong>SkillLint</strong>.</p><h3>Introducing SkillLint: The Ultimate AI Skill Validator</h3><p><a href="https://meet-miyani.github.io/agent-skill-validator/"><strong>SkillLint</strong></a> is a free, live, browser-based validator for AI agent skills. It instantly audits your skill packages to ensure they are clean, safe, and highly optimized for LLMs.</p><p>The best part? <strong>You don’t need to install anything. It is live right now.</strong></p><p>You simply open the web app, drag and drop your skill folder, ZIP archive, or standalone SKILL.md file straight into the browser. Within milliseconds, SkillLint produces a comprehensive, actionable report detailing exactly what needs to be fixed.</p><blockquote>“Privacy is paramount for custom agent logic. SkillLint is 100% local-first. Uploads stay entirely in your browser session — no server is required, and your proprietary code never leaves your machine.”</blockquote><h3>How SkillLint Supercharges Your Agentic Workflows</h3><p>SkillLint takes the guesswork out of AI tool development by running dozens of strict checks across four main pillars:</p><h3>1. Token Budget Optimization 📉</h3><p>LLM context is expensive and finite. SkillLint calculates exact activation tokens, reference subtotals, and rough model cost estimates. It identifies your largest references and helps you keep your context window lean, ensuring your AI stays fast and focused.</p><h3>2. Advanced Security Scanning 🔒</h3><p>Never leak a secret to an LLM again. SkillLint hunts for API-key-like values, private keys, JWTs, hardcoded absolute paths, and risky shell command patterns hidden inside your scripts.</p><h3>3. Reference Graph Healing 🔗</h3><p>It acts as a map-maker for your markdown files. SkillLint detects orphaned references, missing targets, empty files, and broken internal links so your agent never hits a dead end while parsing instructions.</p><h3>4. AI-Powered Auto-Repair 🤖</h3><p>SkillLint doesn’t just point out errors — it helps you fix them. The tool can apply targeted link fixes, auto-link reference mentions, or generate a customized AI repair prompt that you can paste directly into Cursor or ChatGPT to rewrite your skill perfectly.</p><h3>Try the Live Tool Right Now (Zero Setup)</h3><p>Ready to see how your agent skills score? You can use the live tool immediately.</p><ol><li><strong>Visit the Live App:</strong> Go to the <a href="https://meet-miyani.github.io/agent-skill-validator/">SkillLint Web App</a>.</li><li><strong>Drag &amp; Drop:</strong> Drop your skill folder or .skill bundle directly into the UI.</li><li><strong>Review &amp; Repair:</strong> Inspect your quality score, fix the highlighted risks, and use the built-in repair tools.</li><li><strong>Export:</strong> Download your perfectly tuned, LLM-ready package as a clean ZIP.</li></ol><p><a href="https://meet-miyani.github.io/agent-skill-validator/">🚀 Launch the Free Live Validator</a></p><h3>Open Source: Build, Customize, and Contribute</h3><p>While the live tool is the easiest way to get started, <strong>SkillLint is completely open-source</strong>. If you are a developer who loves to tinker, you can easily pull down the repo, run it locally, or customize the validation rules for your own internal agent frameworks.</p><p>Getting started locally requires Node &gt;=20 and takes just two commands:</p><pre>npm install<br>npm run dev</pre><p><a href="https://github.com/Meet-Miyani/agent-skill-validator">⭐ View Source Code on GitHub</a></p><p>Contributions are incredibly welcome! Whether you want to add new validation rules, improve the report UI, or add edge cases for real-world skill packages, feel free to open a PR.</p><h3>The Future of AI Coding is Quality Tools</h3><p>As we transition from simple AI copilots to fully autonomous AI agents, the quality of the tools we provide becomes the ultimate bottleneck. We wouldn’t push production software without running a linter or writing unit tests. It’s time we treat AI skills with the exact same rigor.</p><p>Whether you are optimizing a single SKILL.md or auditing a massive library of agentic tools, SkillLint guarantees you are shipping context-efficient, secure, and reliable instructions to your models.</p><p><em>If this tool saves you debugging time and API costs, please consider dropping a ⭐️ on the </em><a href="https://github.com/Meet-Miyani/agent-skill-validator"><em>GitHub repo</em></a><em>. Happy agent building!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=077c973fa9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native vs KMP vs Native: Cross-Platform Guide]]></title>
            <link>https://meet-miyani.medium.com/react-native-vs-kmp-vs-native-cross-platform-guide-cae169592029?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae169592029</guid>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 05:39:50 GMT</pubDate>
            <atom:updated>2026-04-23T05:39:50.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Native vs KMP vs Full Native: The Cross-Platform Mobile Guide That Doesn’t Waste Your Time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bhg5F-7UqpmLnlpoQWIywg.png" /></figure><h4>Three real options. One honest comparison. And the one factor that flips the entire decision — which most guides conveniently skip.</h4><p>Every mobile team hits the same wall eventually. You’re maintaining two codebases, duplicating bugs across platforms, and watching your iOS and Android features slowly drift apart like estranged siblings at a family wedding. So someone in a meeting says the dreaded words — <em>“What if we go cross-platform?”</em> — and suddenly everyone has opinions, ego, and a Medium article to share.</p><p>So here’s mine. But I’ll try to actually be useful.</p><p>This guide covers the three real options in 2026: <strong>React Native</strong>, <strong>Kotlin Multiplatform / Compose Multiplatform (KMP/CMP)</strong>, and just <strong>staying Full Native</strong>. I’ll cut through the marketing copy and give you what actually matters — especially if your app has custom UI. And if it does, buckle up, because that changes everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJMjKketmUYdaXO8bU3XAA.png" /></figure><h3>Where Things Actually Stand in 2026</h3><p>Before we pick sides, let’s establish where things actually stand. These aren’t just blog opinions — the frameworks have genuinely evolved.</p><h4>React Native</h4><p><strong>React Native</strong> is at v0.84 (February 2026). The Legacy Architecture is completely gone — RN 0.82 dropped it, and 0.84 cleaned up the binaries. Hermes V1 is now default. The New Architecture (Fabric + JSI + TurboModules) is the only architecture. It’s a more capable RN than 2022, but structurally, it’s still a JS runtime inside your app.</p><h4>KMP / CMP</h4><p><strong>KMP/CMP</strong> has had a proper glow-up. Google officially declared KMP stable for business logic sharing in late 2023. Compose Multiplatform (the UI layer) reached stable on iOS in CMP 1.8.0 (May 2025), and CMP 1.10.0 added unified Previews, Navigation 3, and stable Compose Hot Reload. KMP has surged from 12% to 23% market share in 18 months — the fastest-growing cross-platform option right now.</p><h4>Full Native</h4><p><strong>Full Native</strong> is unchanged and unbothered. Jetpack Compose on Android and SwiftUI on iOS are both mature. If your team is already here, nothing has changed — except the duplication problem continues to compound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCxxh9yjnPnBXAfcBoVevg.png" /></figure><h3>The Thing Everyone Forgets: Custom UI Changes Everything</h3><p>Most framework comparisons assume your app uses standard native widgets — buttons, tab bars, bottom sheets, system alerts. If that’s you, fine. But if your app has <strong>custom animations, bespoke design systems, or pixel-perfect branded UI</strong>, those comparisons are basically useless for your situation.</p><blockquote>If your app doesn’t use native widgets anyway, React Native’s “real native views” advantage evaporates entirely.</blockquote><p>Here’s how custom UI reshapes the decision at every layer:</p><p><strong>React Native’s main selling point</strong> is that it renders actual native UIKit/Android views. On a screen full of custom-drawn components? That advantage is irrelevant — you’re not using those native views anyway.</p><p><strong>CMP’s Skia canvas</strong> is literally built for custom rendering. Your custom card animation, your branded progress ring, your fancy onboarding screen — Skia draws all of it identically on both iOS and Android. No “does this look right on iOS?” second-guessing.</p><p><strong>The “CMP doesn’t feel native on iOS”</strong> criticism? Valid — for standard system UI. Completely moot if your app’s UI is custom-designed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDl-7Z6qoLpyhuIha7aTBg.png" /></figure><h3>KMP vs CMP: They’re Not Competitors — They’re Layers</h3><p>A lot of people treat KMP and CMP as two separate options. They’re not. Think of them as a stack you can opt into at different depths:</p><p><strong>KMP (the foundation)</strong> shares your business logic — networking, domain models, ViewModels, repositories, data persistence. Your UI stays native on each platform. This is the lowest-risk, highest-ROI starting point.</p><p><strong>CMP (the optional layer on top)</strong> takes it further and shares the UI too — Compose composables rendered via Skia on iOS, standard Compose on Android. Same code, same pixels, both platforms.</p><p>The recommended path is simple: <em>start with KMP, graduate to CMP</em>. Don’t try to do both at once on a production app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WeOpXXGp93rB7tYmy3nEQ.png" /></figure><h3>Performance: Let’s Put Numbers On It</h3><p>Performance debates in cross-platform usually devolve into vibes and anecdote. So here are the actual benchmarks as of 2026:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzzEbP_IC8-uv8yQ6zmP1Q.png" /></figure><p>The RN gap matters most in two scenarios: <strong>custom animations</strong> and <strong>large list rendering</strong>. RN animations must avoid the JS thread entirely (via Reanimated’s native driver) or you’ll get jank. FlatList requires constant tuning. KMP/CMP and native don’t have this problem — their animation logic compiles directly to native code.</p><p>Frame budgets are unforgiving at 120Hz. You have <strong>8.33ms</strong> to render each frame on an iPhone with ProMotion. If your JS thread is doing heavy work, you’ll miss that deadline. Users will feel it even if they can’t name it.</p><h3>OTA Updates: The Double-Edged Sword</h3><p>React Native’s OTA story (via Expo EAS Update) is genuinely one of its best features. Push a JS bundle update, users get it without a store release. Ship a fix in an hour. It sounds incredible — and it is, right up until it isn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwVa-lI61Md40VZVp8h1Zw.png" /></figure><p>Google Play has similar restrictions: apps may not modify or replace themselves outside Google Play’s update mechanism, with an explicit exception for code running in a VM with indirect API access — which is exactly how RN’s JS works. So technically, RN OTA is on firmer ground on Android, but the iOS risk is real.</p><p>The practical rule: use OTA as a <strong>safety valve</strong> for copy fixes, minor UI tweaks, and crash hotfixes. Don’t use it as a feature delivery mechanism, and absolutely don’t use it to change anything related to payments or permissions.</p><p>KMP/CMP and native don’t have OTA. They also don’t have the compliance headache that comes with it.</p><h3>Security &amp; Payments</h3><p>Payment handling deserves its own discussion because the security posture of each framework is materially different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FH5JCA9TMjbY6KrbNq6bKQ.png" /></figure><p>For payment flows specifically: regardless of which framework you pick, integrate payment provider SDKs at the <strong>native layer</strong>. Never store raw card data on device. Always use platform secure storage — iOS Keychain, Android Keystore. These rules apply universally.</p><p>On store rules: if your app sells <strong>physical goods or services</strong> consumed outside the app (food delivery, e-commerce, ride-hailing), Apple allows non-IAP payments and Google Play doesn’t require Play Billing. Digital content is a different story — IAP/Play Billing is mandatory. Worth verifying your exact category.</p><h3>Who’s Actually Using This in Production?</h3><p>Framework debates are fun in theory. Production data is more convincing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DaSQ57ujaDYWXAszfHZkA.png" /></figure><p>The KMP roster includes a payment processor at 6.5M monthly transactions and a fintech app running for 7 years. If that doesn’t put the “KMP isn’t production-ready” argument to rest, nothing will.</p><h3>The Head-to-Head: What Actually Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V9kY5CROd4Vx6ihHuNSlA.png" /></figure><h3>The Adoption Roadmap (for KMP/CMP)</h3><p>If KMP/CMP is the direction, don’t try to migrate everything at once. The phased approach is the only sane one for a production app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0of5fvG8mnuz435PNCEifw.png" /></figure><h3>The Decision Matrix (for Humans)</h3><p>Stop overthinking it. Run through this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cudVAYAIedFPnZR6Nn8EMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XsE_jVDEUDUhNMeoRJAxA.png" /></figure><h3>The Bigger Takeaway</h3><p>Most cross-platform decisions go wrong not because the team picked the wrong framework, but because they picked a framework optimised for a different team’s profile. React Native makes enormous sense if you have React engineers or want to share code with a web team. KMP/CMP makes enormous sense if you have a Kotlin-first Android team and a custom UI. Neither is universally right.</p><p>The question to ask isn’t “which framework is best?” It’s “which framework fits the team we actually have, the app we actually built, and the direction we actually want to go?”</p><p>Answer that honestly — without the hype — and the decision usually becomes obvious.</p><h3>Quick Reference</h3><ul><li><strong>React Native v0.84</strong> — New Architecture only, Hermes V1, Fabric renderer, React 19, OTA via Expo EAS</li><li><strong>KMP</strong> — Stable since Nov 2023, Google-endorsed, compiles to native via LLVM on iOS, AndroidX libraries gaining KMP support</li><li><strong>CMP 1.10.0</strong> — iOS Stable since 1.8.0 (May 2025), Skia/Metal on iOS, 120fps ProMotion confirmed, Navigation 3, Compose Hot Reload</li><li><strong>Performance:</strong> Native (100%) &gt; KMP/CMP (95–100%) &gt; React Native (80–90%)</li><li><strong>OTA:</strong> React Native only. Apple Guideline 2.5.2 applies. Keep it a safety valve, not a feature channel.</li><li><strong>Custom UI:</strong> CMP’s Skia rendering is the correct answer. RN’s native view advantage doesn’t apply.</li><li><strong>Production validation:</strong> McDonald’s (6.5M payments/month, KMP), Cash App (7 years, KMP), HelloFresh (consolidation, RN), Shopify (scale, RN)</li></ul><p><em>Working through a cross-platform decision on your own team? Drop a comment — always curious how others are weighing these trade-offs in practice.</em></p><p><strong>Tags:</strong> React Native Kotlin Multiplatform KMP Compose Multiplatform Cross-Platform Mobile iOS Development Android Development Mobile Architecture Jetpack Compose SwiftUI Mobile Performance Mobile Engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae169592029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Reduced POS Receipt Image Size by 93% — From 81KB Down to 5KB]]></title>
            <link>https://meet-miyani.medium.com/how-we-reduced-pos-receipt-image-size-by-93-from-81kb-down-to-5kb-dd7a456fcd3a?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd7a456fcd3a</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[thermal-printer]]></category>
            <category><![CDATA[image-optimization]]></category>
            <category><![CDATA[imagemagick]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 14:59:59 GMT</pubDate>
            <atom:updated>2026-04-22T14:59:59.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>How We Reduced POS Receipt Image Size by 93% — From 81KB Down to 5KB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QtRGs-Kg2dcpVCj7h_cGw.png" /></figure><h4>A thermal printer doesn’t care about your beautiful design system. It only speaks one language: black dot, or no dot.</h4><p>There’s a specific kind of developer conversation that starts as a bug investigation, turns into a rabbit hole, and ends with someone saying <em>“wait — we’ve been doing this completely wrong the whole time.”</em></p><p>This is one of those stories.</p><p>It started in an R&amp;D group chat. A bug report came in, suspected to be on the mobile side. It wasn’t. But buried inside that discussion was a throwaway comment about the size of receipt images being generated on the backend. Nobody had thought too deeply about it.</p><p>Until we did. And a single afternoon later, we had a 93% file size reduction — with zero loss in print quality. Actually, the print quality got <em>better</em>.</p><h3>A Brief History of How We Got Here</h3><p>Our Android app runs on POS devices at restaurant locations. When an order is placed, the device needs to print a receipt. Simple premise. But <em>how</em> we arrived at our current approach is a small evolution that explains exactly why the size problem existed.</p><h4>Phase 1 — Direct Text Printing (The ESC/POS Era)</h4><p>In the beginning, we printed receipts the classic way. The app constructed plain text strings and sent them directly to the thermal printer via the device’s native SDK — raw ESC/POS commands that told the printer what to do:</p><pre>RESTAURANT NAME<br>--------------------------------<br>1x Item Name             SAR 25<br>1x Another Item          SAR  5<br>--------------------------------<br>TOTAL                    SAR 30</pre><p>The commands were tiny. The printer understood them natively. File size? Roughly 500 bytes. Fast, lean, no drama.</p><p>But here’s the catch: <strong>you have basically zero control over design</strong>. Custom font? Nope. Dynamic logo placement? Sort of. Move a field 3 pixels to the left? Good luck. ESC/POS text mode is a typewriter from 1984 — reliable, but inflexible.</p><h4>Phase 2 — On-Device Image Generation</h4><p>We moved to generating the receipt as a <strong>bitmap image directly on the device</strong>. We could now render anything — custom fonts, RTL text, logos, dynamic dividers, brand colors in previews. Total freedom.</p><p>The receipt was rendered like a mini view, converted into a bitmap, and that bitmap was handed to the printer SDK. Beautiful.</p><p><em>Until it wasn’t.</em></p><p>Every time we needed to tweak the receipt layout — add a new field, resize a section, change a font — we had to ship a new APK update. Anyone who’s worked with POS device fleets knows that getting an update deployed across every device in the field is not “push a button and go home early.”</p><h4>Phase 3 — Server-Side Image Generation</h4><p>The natural solution: <strong>move image generation to the backend</strong>.</p><p>The server generates the receipt image, uploads it, and sends the app a URL. The app downloads the image and sends it to the printer. Now we can change the receipt design with zero APK deployment, zero device coordination, zero waiting.</p><p>Clean architecture. The problem, however, had quietly started unpacking its bags.</p><h3>The Problem Nobody Was Measuring</h3><p>Once image generation moved to the backend, nobody audited what those images actually weighed.</p><p>They looked fine on screen. They printed fine. Nobody complained. So: shipped, and forgotten.</p><p>When we finally pulled up the actual numbers, receipts were coming in at <strong>60KB to over 100KB per image</strong>, with complex orders pushing close to 200KB.</p><p>For context, our specific test receipt — a regular, real-world order — was sitting at <strong>81KB</strong>.</p><p>Now, 81KB is nothing for a webpage. But consider what’s actually happening here:</p><ul><li>A thermal printer is a <strong>1-bit machine.</strong> It either burns a black dot, or it doesn’t. Full stop.</li><li>The receipt content is almost entirely <strong>black text on a white background.</strong></li><li>This image is downloaded over a <strong>mobile connection on a POS device</strong>, on every single order.</li><li>It then gets <strong>loaded into memory</strong> to be passed to the printer SDK.</li></ul><p>We were shipping a truckload of furniture to deliver a single letter.</p><h3>The Diagnosis: What Was Actually Inside That 81KB?</h3><p>A standard image generated by any server-side library — canvas render, HTML screenshot, Puppeteer screenshot — comes out as a <strong>24-bit or 32-bit image by default</strong>.</p><p>Here’s what that means in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*tayiRVmNZqoBcoiwm_kMdw.png" /><figcaption><em>The format gap we were silently paying for on every receipt.</em></figcaption></figure><p>The server was saving <strong>32 bits of color information per pixel</strong> — enough to remember whether each dot was one of <em>4.29 billion</em> possible shades — on an image that used exactly two colors.</p><p>On top of that, standard rendering engines use <strong>anti-aliasing</strong>: they add subtle gray pixels along the curved edges of text to make it look smooth on high-DPI screens. This is exactly what you want on a display. It is completely useless for a thermal printer, which has no concept of gray.</p><p>So the image was carrying:</p><ul><li>Gray anti-aliased pixels the printer had to guess at</li><li>4+ billion unused color possibilities encoded per pixel</li><li>Embedded metadata: creation timestamp, software signature, color profile of a monitor that will never display this receipt, DPI settings for a screen that doesn’t exist in this workflow</li></ul><p>All invisible. All weight.</p><h3>Where the Insight Actually Came From</h3><p>Here’s the honest version of this story, because it matters.</p><p>The core idea didn’t come from an AI assistant. It came from having done enough bitmap work on Android to know how images <em>actually</em> sit in memory — x/y pixel grids, bits per pixel, what a color channel really costs. Once you’ve looked at an image at that level, you stop seeing “a receipt” and start seeing <em>what’s actually encoded in every pixel</em>.</p><p>There’s a small analogy I kept coming back to during the debugging session: <strong>a photo taken in daylight is almost always larger than the same scene shot at night.</strong> Not because the camera tried harder — because daylight exposes more color, more gradients, more variation. More <em>information</em> to encode. Night shots collapse into darker, flatter tones. Less entropy, smaller file.</p><p>A receipt is the extreme version of a night shot. It’s basically two tones. So why were we encoding it like a daylight photo with 4.29 billion possible colors per pixel?</p><p>That’s the frame that unlocked everything: <strong>keep only the colors you actually need, and match the encoding to what the hardware can physically render.</strong></p><h4>Where AI Actually Helped</h4><p>Once the direction was clear, I used an AI assistant the way I’d use a well-read colleague at 2 AM — not to find the answer, but to pressure-test it and speed up the boring parts:</p><ul><li>Confirming ImageMagick flag behavior without digging through three layers of man pages</li><li>Sanity-checking <em>why</em> JPEG produces mosquito noise on sharp edges (so I could explain it, not just avoid it)</li><li>Comparing PNG color-type modes and their compression characteristics</li><li>Validating that png:color-type=3 + bit-depth=1 was genuinely the optimal combo and not just <em>a</em> working combo</li></ul><p>That’s the honest role AI played here — a research accelerator on top of an insight that came from knowing how bitmaps work. It won’t replace engineers who understand their systems. But once you know <em>what</em> you’re looking for, it’s a pretty great way to stop Googling and start shipping.</p><h3>The Solution: 1-Bit PNG + Full Metadata Strip</h3><p>The fix has three parts, each one compounding the last.</p><h4>1. Convert to 1-Bit Monochrome</h4><p>Force the image into exactly 2 colors: pure black and pure white. No shades, no palette, no gray.</p><p>The math is almost satisfying in how obvious it becomes in hindsight:</p><blockquote>32 bits per pixel → 1 bit per pixel = <strong>32× less raw data, before compression even starts</strong></blockquote><h4>2. Kill the Anti-Aliasing with a Hard Threshold</h4><p>Apply a 50% brightness threshold during conversion: any pixel darker than halfway becomes pure black, everything else becomes pure white. The anti-aliased gray fringe around every character is completely eliminated. The printer now receives data it was literally built to consume.</p><h4>3. Strip All Metadata Chunks</h4><p>PNG files carry hidden “chunks” — packets of metadata that live inside the file but have zero effect on pixels. Color profiles, software credits, timestamps, gamma tables, DPI hints. None of these mean anything to a thermal printer. We remove all of them.</p><h3>The Implementation: One ImageMagick Command</h3><p>For the actual processing, we used <strong>ImageMagick</strong> — specifically the convert CLI tool (or magick on version 7+). Free, battle-tested, runs on any server, and handles this in a single command:</p><pre>convert input.jpg \<br>  -threshold 50% \<br>  -monochrome \<br>  -strip \<br>  -define png:exclude-chunk=all \<br>  -define png:color-type=3 \<br>  -define png:bit-depth=1 \<br>  output.png</pre><p>Breaking down each flag:</p><p><strong>-threshold 50%</strong> — The anti-aliasing killer. Pixel below 50% brightness? Pure black. Above? Pure white.</p><p><strong>-monochrome</strong> — Reinforces strict 1-bit conversion. No grayscale leaks through.</p><p><strong>-strip</strong> — Removes standard EXIF data, embedded color profiles, and common metadata.</p><p><strong>-define png:exclude-chunk=all</strong> — The nuclear option. Drops <em>every</em> non-essential PNG metadata chunk: software tags, timestamps, calibration data, all of it.</p><p><strong>-define png:color-type=3</strong> — Forces indexed palette mode — the most efficient possible encoding for exactly 2 colors.</p><p><strong>-define png:bit-depth=1</strong> — Explicitly sets 1-bit depth. One bit. Two states. Perfect hardware match.</p><p>Want to squeeze out the absolute last few bytes? Run the output through optipng, a dedicated PNG lossless optimizer that tightens the internal DEFLATE compression without touching a single pixel:</p><pre>optipng -o7 -strip all output.png</pre><h3>“But What About JPEG? Or WebP?”</h3><p>Both come up. Both are the wrong answer for this use case.</p><p><strong>JPEG</strong> is designed for photographs — smooth gradients, natural scenes. When you apply JPEG compression to sharp black text on a white background, it produces what’s called “mosquito noise”: blurry gray halos around every character caused by the algorithm struggling with hard edges it wasn’t designed for. The printed text looks fuzzy, and counterintuitively, the JPEG is <em>larger</em> than the 1-bit PNG. You pay more, get worse output. Pass.</p><p><strong>WebP</strong> is excellent for web images, but most thermal printer SDKs don’t natively support it. The mobile app would have to decode WebP into a raw bitmap before sending it to the printer — extra CPU, extra RAM, extra failure points. And for a pure black-and-white image, WebP’s size advantage over a 1-bit PNG is essentially zero. More complexity, zero benefit.</p><p><strong>1-bit PNG is the correct answer.</strong> Every time. For receipts.</p><h3>The Results — Real Numbers, Real Receipt</h3><p>Here’s the actual before and after, measured on a real production receipt image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*yljoypESAQTTkcDAhKsHuw.png" /><figcaption><em>Same receipt, same print quality — 93% less file.</em></figcaption></figure><p>Five kilobytes. For a complete restaurant receipt — logo, multi-language text (yes, this works for Arabic, Hebrew, Latin, anything), itemized order, prices, totals, and footer.</p><p>The mobile app downloads it faster. The device memory footprint is smaller. The printer renders it faster because the SDK doesn’t need to run any color conversion math. And the printed text is actually <em>crisper</em> because gray anti-aliased pixels are no longer being dithered into unpredictable black dots.</p><h3>One More Thing: Width Matters Too</h3><p>While we’re here — if you’re generating receipt images on a backend, always generate at the <strong>exact pixel width your printer expects</strong>. Don’t let the app scale it.</p><ul><li><strong>58mm paper</strong> → 384px wide</li><li><strong>80mm paper</strong> → 576px wide</li></ul><p>If the image comes down at the wrong width, the device has to rescale it before printing — burning CPU, potentially introducing blur, and sometimes misaligning content. Generate correctly from the start.</p><p>For height: let it be <strong>dynamic</strong> based on order content. Fixed heights lead to either cut-off receipts or a lot of blank paper rolling out at the end, which restaurant partners will absolutely notice and complain about.</p><h3>The Bigger Takeaway</h3><p>This whole situation is a reminder that <strong>library defaults are designed for the general case, not your specific case</strong>.</p><p>Standard image libraries default to 32-bit because it works for everything. Rendering engines default to anti-aliasing because screens need it. Backend servers generate images without asking who the consumer actually is.</p><p>None of those defaults are wrong. They just weren’t right <em>for us</em>.</p><p>The moment we asked “what does a thermal printer actually need?” — and remembered how images are actually stored at the pixel level — the answer was obvious. A 93% improvement came out of a single CLI command, backed by a first-principles look at the format itself.</p><p>Sometimes the best optimization isn’t a clever algorithm or a new architecture pattern. It’s understanding the hardware you’re talking to, and speaking its language.</p><h3>Quick Reference Checklist</h3><p>If you’re generating receipt images for POS thermal printers, run through this before shipping:</p><ul><li>Output format: <strong>PNG</strong> (not JPEG, not WebP)</li><li>Color depth: <strong>1-bit monochrome</strong> (exactly 2 colors)</li><li>Apply <strong>50% threshold</strong> to eliminate anti-aliased gray edges</li><li>Strip <strong>all metadata</strong> — EXIF, color profiles, software tags, timestamps</li><li>Image width: <strong>exact printer pixel width</strong> (384px for 58mm / 576px for 80mm)</li><li>Image height: <strong>dynamic</strong> based on content length</li><li>Optional: run through optipng -o7 for maximum lossless compression</li></ul><p>One command and you’re done. Your mobile app, your POS device, and whoever pays the bandwidth bill will all thank you.</p><p><em>Built something similar? Got a different approach? Drop a comment — always curious how others are handling POS receipt pipelines.</em></p><p><strong>Tags:</strong> Android POS Thermal Printing Image Optimization ImageMagick Backend Mobile Development Performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd7a456fcd3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Skill for Compose & Compose Multiplatform]]></title>
            <link>https://meet-miyani.medium.com/ai-skill-for-compose-compose-multiplatform-5fb2e56368ae?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb2e56368ae</guid>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 07:10:02 GMT</pubDate>
            <atom:updated>2026-03-21T07:10:02.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r6hAxWegp50se-yTkMhYA.jpeg" /></figure><blockquote><em>An open-source agent skill for Cursor, Codex, and Claude Code that teaches AI how to write production-grade Jetpack Compose and Compose Multiplatform (KMP) code.</em></blockquote><p>I use AI coding tools every day. Cursor, Codex, Claude Code — they’re part of my workflow now. And for most things, they’re great. But every time I asked them to write <strong>Jetpack Compose</strong> or <strong>Compose Multiplatform</strong> code, I kept running into the same problems.</p><p>The code would compile. It would even look clean. But it was wrong in ways that only show up later — when the app grows, when you need to test it, when you ship it to real users on Android, iOS, and Desktop.</p><p>So I built something to fix it.</p><h3>The Problem: AI Writes Compose Code That Doesn’t Scale</h3><p>Let me be specific. Here’s what I kept seeing from every AI coding assistant I tried:</p><p><strong>On the Jetpack Compose side (Android):</strong></p><ul><li>Business logic crammed directly inside @Composable functions — parsing numbers, running validation, computing results, all during composition</li><li>mutableStateOf scattered across composables instead of a proper StateFlow in the ViewModel</li><li>One-shot events like snackbar messages and navigation modeled as boolean flags in state (showSnackbar = true) — a classic bug factory</li><li>Material 2 APIs instead of Material 3</li><li>String-based navigation routes when type-safe routes have been the standard since Navigation Compose 2.8+</li><li>Zero awareness of <strong>recomposition</strong> — the single biggest performance concern in Compose</li></ul><p><strong>On the Compose Multiplatform side (KMP/CMP), it got worse:</strong></p><ul><li>AI confidently recommending AndroidX libraries in commonMain that <strong>don&#39;t publish multiplatform artifacts</strong> — your project just won&#39;t compile on iOS</li><li>No understanding of when to use expect/actual vs interfaces for platform-specific code</li><li>Using Android’s R.string and R.drawable instead of CMP&#39;s Res.string and Res.drawable</li><li>Ignoring platform differences like iOS safe areas, keyboard behavior, and haptics</li><li>Picking the wrong Ktor engine — OkHttp works on Android, but you need Darwin for iOS and CIO for Desktop</li></ul><p>The core issue? <strong>AI tools have general Kotlin knowledge but zero architectural judgment for Compose.</strong> They don’t understand unidirectional data flow. They don’t know which libraries are Android-only vs truly multiplatform. They don’t think about recomposition performance. They just generate code that looks right.</p><p>This is the “vibe coding” trap. The code compiles, the AI sounds confident, but you’re building on a broken foundation. And with <strong>Compose Multiplatform</strong>, the bugs are even sneakier — they hide across targets. Works on Android, crashes on iOS.</p><h3>What I Built: compose-skill</h3><p><a href="https://github.com/Meet-Miyani/compose-skill"><strong>compose-skill</strong></a> is not a library. It’s not documentation. It’s an <strong>AI agent skill</strong> — a portable knowledge pack that you install once, and your AI coding tool gains production-grade understanding of the entire Compose ecosystem.</p><p>If you’re not familiar with agent skills: they’re an open standard for teaching AI tools domain-specific expertise. Think of it as giving your AI assistant a senior Compose engineer’s brain. It works with <strong>Cursor</strong>, <strong>OpenAI Codex</strong>, and <strong>Claude Code</strong> today.</p><p>The skill covers both <strong>Jetpack Compose</strong> (Android-only) and <strong>Compose Multiplatform</strong> (Android + iOS + Desktop + Web). This isn’t an afterthought — CMP is treated as a first-class target throughout. The skill knows which libraries actually publish KMP artifacts and which are Android-only. It knows when to use Hilt (Android) vs Koin (multiplatform). It knows the difference between R.string and Res.string.</p><p>Here’s what it covers:</p><ul><li><strong>Architecture:</strong> MVI with Event, State, Effect. ViewModel patterns. State modeling for forms, calculators, and complex screens.</li><li><strong>Compose UI:</strong> Material 3 theming, animations (shared elements, gesture-driven, Canvas), lists/grids/pagers, accessibility and WCAG compliance.</li><li><strong>Navigation:</strong> Navigation 3 with NavDisplay, user-owned back stack, scenes (dialog, bottom sheet, list-detail adaptive), modularization. Plus Nav 2 compatibility for existing codebases.</li><li><strong>Data layer:</strong> Ktor HTTP client with auth and token refresh, Room Database, DataStore (Preferences and Typed), Paging 3 with MVI integration.</li><li><strong>Performance:</strong> 20 recomposition rules, Compose Compiler Metrics, baseline profiles, text input performance, stability annotations.</li><li><strong>Cross-platform:</strong> commonMain sharing strategy, expect/actual vs interface decision guide, iOS Swift interop with SKIE, CMP resources (Res.string, Res.drawable), platform bridge patterns.</li><li><strong>Build and ship:</strong> Gradle with version catalogs, AGP 9+, convention plugins, CI/CD with GitHub Actions, desktop packaging (DMG/MSI/DEB), signing and notarization.</li></ul><p>Structurally, it’s <strong>1 core SKILL.md file + 26 deep-dive reference files</strong>. The main file handles 80% of cases. The references get loaded only when the AI needs deeper guidance on a specific topic — navigation details, Ktor setup, Room migrations, etc. This keeps the context window efficient.</p><p>Check it out: <a href="https://github.com/Meet-Miyani/compose-skill"><strong>github.com/Meet-Miyani/compose-skill</strong></a></p><h3>Before vs After: What Changes</h3><p>Let me show you what the skill actually fixes. These are real patterns.</p><h4>1. State Management in Jetpack Compose</h4><p><strong>Without the skill</strong> — AI puts everything inside the composable:</p><pre>@Composable<br>fun LoanCalculatorScreen() {<br>    var amountText by rememberSaveable { mutableStateOf(&quot;&quot;) }<br>    var rateText by rememberSaveable { mutableStateOf(&quot;&quot;) }<br>    var yearsText by rememberSaveable { mutableStateOf(&quot;&quot;) }<br><br>    val amount = amountText.toDoubleOrNull() ?: 0.0<br>    val rate = rateText.toDoubleOrNull() ?: 0.0<br>    val years = yearsText.toIntOrNull() ?: 0<br>    val isValid = amount &gt; 0.0 &amp;&amp; rate &gt; 0.0 &amp;&amp; years &gt; 0<br>    val monthlyPayment = if (isValid) {<br>        val monthlyRate = rate / 1200.0<br>        val months = years * 12<br>        (amount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months.toDouble()))<br>    } else 0.0<br>    Column {<br>        OutlinedTextField(value = amountText, onValueChange = { amountText = it })<br>        Text(&quot;Monthly payment: $monthlyPayment&quot;)<br>        Button(enabled = isValid, onClick = { /* save */ }) { Text(&quot;Calculate&quot;) }<br>    }<br>}</pre><p>Looks fine, right? But it’s doing validation, parsing, and business calculations inside composition. You can’t unit test any of it. State is forked across multiple mutableStateOf holders. Every keystroke triggers recalculation. This doesn&#39;t scale.</p><p><strong>With the skill</strong> — MVI with Event, State, Effect:</p><pre>sealed interface LoanEvent {<br>    data class OnAmountChanged(val amount: String) : LoanEvent<br>    data class OnRateChanged(val rate: String) : LoanEvent<br>    data object OnCalculateClick : LoanEvent<br>}<br><br>data class LoanState(<br>    val amount: String = &quot;&quot;,<br>    val rate: String = &quot;&quot;,<br>    val isSaving: Boolean = false,<br>    val errors: Map&lt;String, String&gt; = emptyMap()<br>) {<br>    val canCalculate: Boolean get() = amount.isNotBlank() &amp;&amp; rate.isNotBlank()<br>}<br>sealed interface LoanEffect {<br>    data class ShowMessage(val text: String) : LoanEffect<br>}</pre><p>Events describe what the user did. State describes what to render. Effects describe one-shot actions. The ViewModel owns all logic through a single onEvent() entry point. Clean, testable, scalable.</p><h4>2. One-Shot Events (Snackbar, Navigation)</h4><p><strong>Without the skill</strong> — AI puts events in state:</p><pre>data class UiState(<br>    val showSnackbar: Boolean = false,<br>    val snackbarMessage: String = &quot;&quot;<br>)</pre><p>This is a bug. On Android configuration changes, the new collector picks up the state and shows the snackbar again. You need “consume” logic to flip the boolean back. It’s fragile.</p><p><strong>With the skill</strong> — Effects via Channel:</p><pre>private val _effect = Channel&lt;CreateItemEffect&gt;(Channel.BUFFERED)<br>val effect: Flow&lt;CreateItemEffect&gt; = _effect.receiveAsFlow()<br><br>// In onEvent():<br>_effect.trySend(CreateItemEffect.ShowMessage(&quot;Saved&quot;))</pre><p>Effects fire once and are gone. No replay, no consume logic, no double-showing. The skill even includes a reusable CollectEffect composable that handles lifecycle-aware collection.</p><h4>3. The Compose Multiplatform Trap</h4><p><strong>Without the skill</strong> — AI recommends Android-only code in shared modules:</p><pre>// commonMain — AI generated this, but it won&#39;t compile on iOS<br>import android.content.Context</pre><pre>class HapticFeedback(private val context: Context) {<br>    fun vibrate() { /* Android-only API */ }<br>}</pre><p>Or worse, it adds an AndroidX dependency to commonMain that doesn&#39;t publish multiplatform artifacts. Your Android build passes, then iOS fails with unresolved references.</p><p><strong>With the skill</strong> — Interface in commonMain, platform implementations via DI:</p><pre>// commonMain<br>interface Haptics {<br>    fun perform(type: HapticType)<br>}<br><br>// androidMain<br>class AndroidHaptics(context: Context) : Haptics { /* ... */ }<br><br>// iosMain<br>class IosHaptics : Haptics { /* ... */ }</pre><p>The skill teaches this pattern — define the contract in shared code, implement per platform, wire with Koin. The ViewModel never imports platform types. Testing is trivial with fakes.</p><h3>How It Works Under the Hood</h3><p>The skill isn’t a flat list of rules. It’s <strong>layered</strong>.</p><p>The main SKILL.md file contains core architecture principles, decision heuristics, and the MVI pattern with code examples. This handles most prompts without loading anything else.</p><p>When the AI needs to go deeper — say, you’re setting up Ktor authentication, or configuring Room migrations, or doing shared element animations — it pulls in the relevant reference file. There are 26 of them, each focused on a single domain. They get loaded on-demand, so your context window isn’t wasted on navigation docs when you’re asking about DataStore.</p><p>What makes this different from just writing rules:</p><p><strong>Decision heuristics, not rigid prescriptions.</strong> The skill doesn’t say “always use MVI.” It says: if the project already uses MVVM and it works, don’t rewrite it. If the project uses 4-type MVI (with a Result type), that’s fine — use it. Only suggest changes when asked or when there are clear architectural violations.</p><p><strong>Dependency verification for Compose Multiplatform.</strong> Before recommending any library for commonMain, the skill instructs the AI to verify that the artifact actually publishes multiplatform targets. Most Jetpack libraries are still Android-only. The AI checks Maven Central coordinates, target support, and API shape before suggesting anything.</p><p><strong>Platform-aware defaults.</strong> Android-only project? Default to Hilt for DI, R.string for resources. Compose Multiplatform project? Default to Koin, Res.string, and expect/actual or interfaces for platform APIs. The skill adapts.</p><p><strong>Anti-pattern detection.</strong> There’s a cross-cutting anti-pattern table that covers 27 common mistakes with concrete “why it hurts” and “better replacement” for each. Plus each reference file has its own domain-specific anti-patterns section.</p><h3>Quick Installation</h3><p>One git clone command. Pick your AI tool:</p><pre># Cursor<br>git clone https://github.com/Meet-Miyani/compose-skill.git ~/.cursor/skills/compose-skill<br><br># Codex<br>git clone https://github.com/Meet-Miyani/compose-skill.git ~/.codex/skills/compose-skill<br><br># Claude Code<br>git clone https://github.com/Meet-Miyani/compose-skill.git ~/.claude/skills/compose-skill</pre><p>After cloning, restart your agent or IDE. The skill activates automatically when your prompt involves Compose, ViewModel, StateFlow, KMP, or any related trigger.</p><p>Full installation guide with per-repo setup and verification steps: <a href="https://github.com/Meet-Miyani/compose-skill"><strong>README on GitHub</strong></a></p><h3>What I Learned Building This</h3><p>A few things surprised me while putting this together.</p><p><strong>Encoding architectural judgment is way harder than writing code.</strong> Writing a ViewModel is easy. Writing rules that teach an AI <em>when</em> to use a ViewModel, <em>how</em> to structure the state, <em>what</em> belongs in effects vs state, and <em>when</em> to break those rules — that’s a different kind of challenge. You have to think about every edge case and every project shape the AI might encounter.</p><p><strong>“Correct” and “production-grade” are not the same thing.</strong> AI can write correct Kotlin. It can even write correct Compose. But production-grade means handling configuration changes, preserving content during refresh instead of showing a spinner, guarding no-op state emissions, keying list items by stable IDs, and a hundred other details that only matter at scale. That gap is what the skill fills.</p><p><strong>The multiplatform angle made it much harder.</strong> For Jetpack Compose, you can say “use StateFlow&quot; and move on. For Compose Multiplatform, you first need to verify that lifecycle-viewmodel publishes KMP targets in your version. Then check if collectAsStateWithLifecycle is available in commonMain. Then figure out whether Koin&#39;s koinViewModel() works across all your targets. Every recommendation needs a multiplatform verification step. That&#39;s why the skill includes it as a core rule.</p><p><strong>Skills are better than rules for complex domains.</strong> Cursor and Codex both support simple rules files. But rules are meant for short coding guidelines — “use tabs not spaces” level stuff. A complex domain like Compose needs structured, layered knowledge with decision trees, code examples, and on-demand references. That’s what agent skills are built for.</p><p>The project is <strong>open source under MIT license</strong>. It has 51 stars on GitHub as of this writing, and contributions are welcome — whether it’s fixing a typo, improving a reference doc, or adding coverage for new Compose APIs.</p><h3>Try It</h3><p>If you build with <strong>Jetpack Compose</strong> or <strong>Compose Multiplatform</strong> and you use AI coding tools, this might save you a lot of cleanup work. Install it once, and your AI stops generating architecture you’ll have to rewrite later.</p><p>It’s free, open source, and works today with Cursor, Codex, and Claude Code.</p><p><a href="https://github.com/Meet-Miyani/compose-skill"><strong>github.com/Meet-Miyani/compose-skill</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb2e56368ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Extensions: A Complete Guide to Extension Functions in Kotlin]]></title>
            <link>https://meet-miyani.medium.com/kotlin-extensions-a-complete-guide-to-extension-functions-in-kotlin-335a04845c45?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/335a04845c45</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 07:48:32 GMT</pubDate>
            <atom:updated>2024-08-26T07:48:32.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*jTvWbIZaH-eSZEV0BktSzg.png" /></figure><p>Let’s explore one of Kotlin’s most underrated features: Extensions! Kotlin allows you to add new functionality to a class or an interface without needing to inherit from it or use design patterns like the Decorator. This is made possible through special declarations known as extensions.</p><p>For example, you can create new functions for a class or an interface from a third-party library that you can’t change. These functions can be used just like they were part of the original class. This is known as an extension function. Additionally, Kotlin also allows you to define new properties for existing classes, called extension properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*9PAEp3fRaS75Y7mq.gif" /><figcaption>What did you just say?</figcaption></figure><p>Let’s take an example to better understand <strong>Kotlin extensions</strong>. Imagine you buy a <strong>car </strong>that comes with its own set of functions and features. However, you might want something extra, like adding new accessories or boosting its performance. Even though you can’t change the car’s original factory settings, you can still enhance it by adding accessories like guards, upgrading the exhaust system, tuning the engine for more power, or even installing interior lights. These additions improve the car without altering its original structure — just like <strong>Kotlin extensions</strong> allow you to add new functionality to a class without modifying the original code. In both cases, the core remains untouched, but the added features (or extensions) give you more options and flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YeH4n3EaSzS6C8NB" /></figure><blockquote>Extensions don’t actually modify the classes they extend. Instead, they allow you to call new functions using dot-notation on variables of that type, without adding new members to the class itself.</blockquote><p>Let’s dive into some example to understand better now!</p><pre>// Base URL for the articles<br>val BASE_URL = &quot;https://medium.com/@miyanimeet02_57894/&quot;<br><br>// Article paths<br>val SIMPLIFYING_CONSTRAINT_LAYOUT = &quot;simplifying-constraint-layout-constraints-programmatically-91adf32e80f9&quot;<br>val ANDROID_BUILD_VARIANTS = &quot;android-apk-build-variants-useful-for-qa-testing-87c1b8f1ea61&quot;<br><br>// Extension function for the String class<br>fun String.toArticleUrl(): String {<br>    return BASE_URL + this<br>}<br><br>fun main() {<br>    // Using the extension function to get the full article URL<br>    val fullArticleUrl = SIMPLIFYING_CONSTRAINT_LAYOUT.toArticleUrl()<br><br>    // Print the original article path<br>    println(&quot;Article Path: $SIMPLIFYING_CONSTRAINT_LAYOUT&quot;)<br><br>    // Print the full article URL<br>    println(&quot;Full Article URL: $fullArticleUrl&quot;)<br>}</pre><p>Here, <strong>toArticleUrl()</strong> is an extension function added to the <strong>String </strong>class. It allows any <strong>String </strong>instance to be treated as an article path and, when called, returns the full URL by appending the <strong>BASE_URL </strong>to the string.</p><p>Outputs:</p><ol><li><strong>Article Path</strong>:<br>simplifying-constraint-layout-constraints-programmatically-91adf32e80f9</li><li><strong>Full Article URL</strong>:<br><a href="https://medium.com/@miyanimeet02_57894/simplifying-constraint-layout-constraints-programmatically-91adf32e80f9">https://medium.com/@miyanimeet02_57894/simplifying-constraint-layout-constraints-programmatically-91adf32e80f9</a></li></ol><p>Here, the <strong>String </strong>class itself isn’t modified, but an extension function is created for it. This lets you use the function with the dot operator on any string. The function prepends the string with <strong>BASE_URL </strong>and returns the result.</p><p>For example, if we use it with <strong>“meet-miyani”</strong></p><pre>fun main() {<br>    val url = &quot;meet-miyani&quot;.toArticleUrl()<br>}</pre><p>This will output:</p><ul><li><a href="https://medium.com/@miyanimeet02_57894/meet-miyani">https://medium.com/@miyanimeet02_57894/meet-miyani</a></li></ul><p>Let’s break down the extension function we created:</p><pre>val BASE_URL = &quot;https://medium.com/@miyanimeet02_57894/&quot;<br><br>// Extension function for the String class<br>fun String.toArticleUrl(): String {<br>    return BASE_URL + this<br>}</pre><p>In this extension function, we use <strong>this </strong>to reference the <strong>String </strong>instance it&#39;s called on. Since this function extends the <strong>String </strong>class, <strong>this</strong> represents the original string. The function returns a value by prepending the <strong>BASE_URL </strong>to <strong>this</strong>.</p><blockquote>It’s important to note that <strong>extension functions don’t always have to return a value </strong>— they can perform actions without returning anything. Here’s an example:</blockquote><pre>// Extension function for the String class<br>fun String.printArticleUrl() {<br>    val articleUrl = BASE_URL + this<br>    println(articleUrl)<br>}</pre><p>In this version, <strong>printArticleUrl() </strong>doesn&#39;t return anything; it simply constructs the full URL and prints it. This shows the flexibility of extension functions in Kotlin—they can either return a value or just perform an action based on the class they extend.</p><p><strong>I hope we’re on the right track, and that you now understand how extensions work in Kotlin.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ZHCg3EhC46y2rrhh.gif" /></figure><p><strong>Now let’s have some real fun with Kotlin Extensions!</strong></p><p>Imagine we want to compare two numbers of different data types. Consider this code:</p><pre>fun main() {<br>    var first: Int? = 5<br>    var second: Double? = 5.01<br>    <br>    val condition = first &gt; second<br>}</pre><p>This will result in a compiler error because the numbers are of different types and both are nullable. While we could force non-nullability by adding <strong>!!</strong> at the end of the variables, that&#39;s not ideal. Using <strong>!!</strong> ignores the possibility that these values could be null, which might lead to a crash if they are.</p><p>Instead, let’s explore how we can solve this more elegantly with Kotlin extension functions!</p><pre>fun Number?.isGreaterThan(number: Number?): Boolean {<br>    if (this == null) return false<br>    if (number == null) return true<br>    return this.toDouble() &gt; number.toDouble()<br>}<br><br>fun Number?.isGreaterThanOrEqualTo(number: Number?): Boolean {<br>    if (this == null) return false<br>    if (number == null) return true<br>    return this.toDouble() &gt;= number.toDouble()<br>}<br><br>fun Number?.isSmallerThan(number: Number?): Boolean {<br>    if (this == null) return true<br>    if (number == null) return false<br>    return this.toDouble() &lt; number.toDouble()<br>}<br><br>fun Number?.isSmallerThanOrEqualTo(number: Number?): Boolean {<br>    if (this == null) return true<br>    if (number == null) return false<br>    return this.toDouble() &lt;= number.toDouble()<br>}</pre><p>I created these extension functions to handle comparisons between any numeric types — whether <strong>Double</strong>, <strong>Float</strong>, <strong>Long</strong>, or <strong>Int</strong>. Notice that the <strong>Number?</strong> type is used, meaning the numbers can be nullable. These functions gracefully handle null values, ensuring that if either number is <strong>null</strong>, the comparison logic still works as expected.</p><p>For example:</p><ul><li>If <strong>this </strong>(the calling number) is <strong>null</strong>, the function returns <strong>false </strong>for &quot;greater than&quot; or &quot;greater than or equal to&quot; comparisons, and <strong>true </strong>for &quot;less than&quot; or &quot;less than or equal to&quot; comparisons.</li><li>If the <strong>number </strong>parameter is <strong>null</strong>, the function treats <strong>this </strong>as greater, or equal, depending on the comparison.</li></ul><p>This approach ensures your comparisons are safe and robust, even when working with nullable values.</p><p>And to use it, pretty simple!</p><pre>fun main() {<br>    var first: Int? = 5<br>    var second: Double? = 5.01<br><br>    val condition = first.isGreaterThan(second)<br>}</pre><p>But there’s more! <strong>Kotlin is like a concise poem</strong> — what if we could write it directly as <strong>first isGreaterThan second</strong>? This would make the statement even more readable, like plain English, right?</p><p>To achieve this, we can use <strong>infix notation</strong>. By adding the <strong>infix </strong>keyword before the function declaration, we can call the function without dots or parentheses, making the code cleaner and more natural to read.</p><p>Here’s how to modify the function:</p><pre>infix fun Number?.isGreaterThan(number: Number?): Boolean {<br>    if (this == null) return false<br>    if (number == null) return true<br>    return this.toDouble() &gt; number.toDouble()<br>}</pre><p>Now, you can write:</p><pre>fun main() {<br>    var first: Int? = 5<br>    var second: Double? = 5.01<br><br>    val condition = first isGreaterThan second<br>}</pre><p>There are many situations where this function can be very useful. For example, in <strong>Android</strong>, you might want to apply or remove a strikethrough on a <strong>TextView</strong>.</p><p>Typically, you would do it like this:</p><pre>// To set the Strike Through<br>textView.paintFlags = textView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG<br><br>// To remove the Strike Through<br>textView.paintFlags = textView.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()</pre><p>However, writing this code every time can be repetitive and messy. Instead, we can create simple extension functions to handle it:</p><pre>fun TextView.setStrikeThrough() {<br> paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG<br>}<br><br>fun TextView.clearStrikeThrough() {<br> paintFlags = paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()<br>}</pre><p>Now, you can easily apply or remove a strikethrough with a simple function call, making your code cleaner and more readable.</p><pre>// To set the Strike Through<br>textView.setStrikeThrough()<br><br>// To remove the Strike Through<br>textView.clearStrikeThrough()</pre><p>Now we understand Kotlin Extensions and the power they bring to our code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*mozCWZ159KTLUws2.gif" /></figure><p><strong>Wrapping Up!</strong></p><p>Kotlin extensions are a powerful tool that can:</p><ul><li>Add new functionality to existing classes without modifying their original code.</li><li>Make your codebase cleaner, more readable, and easier to maintain.</li><li>Provide a flexible and elegant solution for various coding scenarios.</li></ul><p>Now that you have the basics of <strong>Kotlin extensions</strong>, you can start playing around and creating your own. If you come up with any <strong>useful functions</strong>, feel free to share them in the comments so other developers can benefit from them too.</p><p>If you want to dive deeper into Kotlin extensions, here’s the link to the official Kotlin documentation on extension functions.</p><p><a href="https://kotlinlang.org/docs/extensions.html">Extensions | Kotlin</a></p><p>Happy coding!</p><p>Wait, wait, wait! don’t forget to clap and share if you found this article helpful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*SGMkb1WxphA5xmZ2.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=335a04845c45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android APK Build Variants — Useful for QA Testing]]></title>
            <link>https://meet-miyani.medium.com/android-apk-build-variants-useful-for-qa-testing-87c1b8f1ea61?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c1b8f1ea61</guid>
            <category><![CDATA[build-variants]]></category>
            <category><![CDATA[android-build-variant]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 17:39:53 GMT</pubDate>
            <atom:updated>2023-10-23T04:47:55.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android APK Build Variants — Useful for QA Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ejDzgT_wjy1rkPu" /></figure><p>Imagine you’re a developer amidst the hustle of managing different build types — staging, development, and production. Each has unique testing requirements, and the constant switch feels like a juggling act.</p><p>Now, add <strong>QA testers</strong> to the scene, each with their own demands, making environment management a full-time circus act. However, there’s a savior — Android APK Build Variants. They’re like a backstage crew, ensuring everything’s set for each scene. According to the <a href="https://developer.android.com/build/build-variants"><strong>official Android documentation</strong></a>, build variants allow creation of different app versions from one project, easing the management of dependencies and signing configurations. Whether a free or a paid version, build variants handle them seamlessly.</p><h4><strong>Creating Product flavors</strong></h4><p>Creating product flavors is similar to creating build types. Starting from <strong>app/build.gradle</strong> file, Add product flavors to the <strong>productFlavors </strong>block in your build configuration.</p><pre>android {<br>    namespace &#39;avinya.tech.buildvariants&#39;<br>    compileSdk 34<br><br>    defaultConfig {<br>        applicationId &quot;avinya.tech.buildvariants&quot;<br>        minSdk 24<br>        targetSdk 34<br>        versionCode 1<br>        versionName &quot;1.0&quot;<br><br>        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>    }<br><br>    buildTypes {<br>        debug {<br>            minifyEnabled false<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>        }<br>        release {<br>            minifyEnabled false<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>        }<br>    }<br><br>    flavorDimensions &quot;variants&quot;<br>    productFlavors {<br>        development {<br>            applicationId &quot;avinya.tech.buildvariants&quot;<br>            buildConfigField(&quot;String&quot;, &quot;BUILD_TYPE&quot;, &quot;\&quot;${project.property(&#39;DEVELOPMENT_BUILD&#39;)}\&quot;&quot;)<br>            dimension &#39;variants&#39;<br>        }<br><br>        staging {<br>            applicationId &quot;avinya.tech.buildvariants&quot;<br>            buildConfigField(&quot;String&quot;, &quot;BUILD_TYPE&quot;, &quot;\&quot;${project.property(&#39;STAGING_BUILD&#39;)}\&quot;&quot;)<br>            dimension &#39;variants&#39;<br>        }<br><br>        production {<br>            applicationId &quot;avinya.tech.buildvariants&quot;<br>            buildConfigField(&quot;String&quot;, &quot;BUILD_TYPE&quot;, &quot;\&quot;${project.property(&#39;PRODUCTION_BUILD&#39;)}\&quot;&quot;)<br>            dimension &#39;variants&#39;<br>        }<br>    }<br><br>    buildFeatures {<br>        buildConfig = true<br>        viewBinding = true<br>    }<br>}</pre><p>We’ve added <strong>3 flavors</strong> for our product; you can add as per your needs.</p><ul><li><strong>development </strong>— This variant is optimized for rapid development and testing, with configurations set for a debuggable environment.</li><li><strong>staging — </strong>Serving as an intermediary between development and production, this variant is geared towards a testing environment that closely mirrors the production setup but with some debugging capabilities enabled.</li><li><strong>production </strong>— This is the variant that’s ready for release to end-users, with all debugging capabilities disabled and optimizations for performance and security applied.</li></ul><p>Sync the <strong>gradle </strong>with project and now you can select the variant which you want to build from the the drop down menu in Build Variants window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*-qy876A-iCyqZissQas3Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*OMtEi48QYnPZxPIzs-mVZg.png" /></figure><p>Notice the extra element in each block? That’s a <strong>BuildConfig </strong>field, set during the build, helping to identify the active build during runtime.</p><p>Each field is defined in the <strong>gradle.properties</strong> file as shown.</p><pre>DEVELOPMENT_BUILD=developmentBuild<br>STAGING_BUILD=stagingBuild<br>PRODUCTION_BUILD=productionBuild</pre><p>This way, they can be easily accessed within the app.</p><pre>public class MainActivity extends AppCompatActivity {<br><br>    ActivityMainBinding binding;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        binding = ActivityMainBinding.inflate(getLayoutInflater());<br>        setContentView(binding.getRoot());<br><br>        // like this, here the string received will be different for each build<br>        String buildType = BuildConfig.BUILD_TYPE;<br>       <br>    }<br>}</pre><p>Let’s make it more robust and structured now!<br>Start by creating a package <strong>buildutils </strong>and create a enum class <strong>BuildType</strong></p><pre>public enum BuildType {<br><br>    DEVELOPMENT(&quot;developmentBuild&quot;),<br>    STAGING(&quot;stagingBuild&quot;),<br>    PRODUCTION(&quot;productionBuild&quot;);<br><br>    public String getType() {<br>        return type;<br>    }<br><br>    private final String type;<br><br>    BuildType(String type) {<br>        this.type = type;<br>    }<br><br>    public static BuildType fromString(String type) {<br>        for (BuildType buildType : BuildType.values()) {<br>            if (buildType.getType().equals(type)) {<br>                return buildType;<br>            }<br>        }<br>        throw new IllegalArgumentException(&quot;No enum constant found&quot;);<br>    }<br>}</pre><p>Now, this setup looks cleaner and is easier to use. Next, create another class named <strong>BuildUtils </strong>to access the <strong>BuildType.</strong></p><pre>public class BuildUtils {<br><br>    public static BuildType getBuildType() {<br>        return BuildType.fromString(BuildConfig.BUILD_TYPE);<br>    }<br><br>}</pre><p>Now it’s almost done! Now, let’s implement this in <strong>MainActivity</strong>. See the implementation below. It will print the build type in the textView in <strong><em>main_activity.xml</em></strong>.</p><pre>public class MainActivity extends AppCompatActivity {<br><br>    ActivityMainBinding binding;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        binding = ActivityMainBinding.inflate(getLayoutInflater());<br>        setContentView(binding.getRoot());<br><br>        BuildType buildType = BuildUtils.getBuildType();<br><br>        String STAGE_MODE = &quot;STAGING&quot;;<br>        String PRODUCTION_MODE = &quot;PRODUCTION&quot;;<br>        String DEV_MODE = &quot;DEVELOPMENT&quot;;<br><br>        switch (buildType) {<br>            case DEVELOPMENT:<br>                binding.textViewBuildType.setText(DEV_MODE);<br>                break;<br>            case STAGING:<br>                binding.textViewBuildType.setText(STAGE_MODE);<br>                break;<br>            case PRODUCTION:<br>                binding.textViewBuildType.setText(PRODUCTION_MODE);<br>                break;<br>        }<br>    }<br>}</pre><p>You can also give each build variant its own app name and icon, making them easily recognizable. For a detailed walkthrough, check out my implementation on <a href="https://github.com/Meet-Miyani/Build-Variants-Android"><strong><em>Github</em></strong></a>.</p><p><a href="https://github.com/Meet-Miyani/Build-Variants-Android">GitHub - Meet-Miyani/Build-Variants-Android</a></p><p>I hope you found this article insightful and it helps streamline your QA testing process. If you enjoyed the read or found it useful, please show some love by giving it a <strong>clap </strong>👏.</p><p>Your support encourages me to share more of what I learn along my development journey. Feel free to share the article with anyone who might find it beneficial. Thank you for your time, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c1b8f1ea61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Constraint Layout Constraints Programmatically]]></title>
            <link>https://meet-miyani.medium.com/simplifying-constraint-layout-constraints-programmatically-91adf32e80f9?source=rss-8f91a9c1967f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91adf32e80f9</guid>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[constraintlayout]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Meet Miyani]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 11:00:48 GMT</pubDate>
            <atom:updated>2023-10-16T04:57:45.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK-pye-EISc3T3VHJtxZtA.png" /></figure><p><strong>Hey there, Android developers!</strong></p><p>If you’re an Android developer, you’ve likely faced the challenge of making your app’s user interface (UI) responsive across a multitude of different devices. It’s a common struggle, and it can be especially tough when dealing with ConstraintLayout’s ConstraintSet().</p><p>It can be a bit tricky, with syntax that’s easy to forget and functions that might send you running to Google for help. But fear not; I’ve got your back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*EqxaTbD6-DyG1Dlv" /></figure><p>Let’s dive right in.</p><ol><li><strong>Setting up the project<br></strong>Add these two <strong>MaterialTextViews </strong>in the MainActivity.xml, like this which will generate the output shown below in the image.</li></ol><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout <br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:padding=&quot;20dp&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;com.google.android.material.textview.MaterialTextView<br>        android:id=&quot;@+id/textHello&quot;<br>        style=&quot;@style/TextAppearance.Material3.DisplayMedium&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello, &quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;com.google.android.material.textview.MaterialTextView<br>        android:id=&quot;@+id/textName&quot;<br>        style=&quot;@style/TextAppearance.Material3.DisplayMedium&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Meet&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@id/textHello&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;com.google.android.material.button.MaterialButton<br>        android:id=&quot;@+id/btnMoveName&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Move Name&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>2. <strong>Now modifying the ConstraintSets </strong>(Note: I am using ViewBinding here)</p><p><strong>The Traditional Method (Hard to remember): </strong>What we are doing here is modifying the constraints of the “Meet” — “textName”. We are connecting it’s startToStartOf — “<strong>parent</strong>” &amp; topToBottomOf —” <strong>textHello</strong>”.</p><pre>private fun setupViews() {<br>        binding.btnMoveName.setOnClickListener {<br>            moveNameBelowHello()<br>        }<br>}<br><br>private fun moveNameBelowHello(){<br>        with(binding) {<br>            ConstraintSet().apply {<br>                clone(root)<br>                connect(textName.id, ConstraintSet.START, root.id, ConstraintSet.START)<br>                connect(textName.id, ConstraintSet.TOP, textHello.id, ConstraintSet.BOTTOM)<br>                clear(textName.id,ConstraintSet.BOTTOM)<br>                applyTo(root)<br>            }<br>        }<br>}</pre><p>This will move the “Meet” below “Hello” on a click of (<strong>Move Name)</strong> Button.</p><p><strong>Now KTX way (Easy to Use):</strong></p><p>Here’s my contribution to the Android developer community: Kotlin Extension Functions <strong>(KTX Functions)</strong> that can make working with ConstraintSet() a breeze.</p><p>These functions not only simplify the process but also make your code more readable and easier to understand.</p><pre>private fun setupViews() {<br>        binding.btnMoveName.setOnClickListener {<br>            moveNameBelowHello()<br>        }<br>}<br><br>private fun moveNameBelowHello(){<br>        with(binding) {<br>            textName.startToStartOf(root)<br>            textName.topToBottomOf(textHello)<br>            textName.disconnectBottom()<br>        }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*p4AsJFenmoAH-BcW" /><figcaption>Eassyyy!!!, isn’t it ?</figcaption></figure><p>Seems like I have written some statement as it is. But trust me it works like a charm. What I have done here is created a Kotlin Extension function.</p><p>Let me show you one.</p><pre>infix fun View.startToStartOf(target: View) {<br>    ConstraintSet().apply {<br>        clone(parent as ConstraintLayout)<br>        connect(id, ConstraintSet.START, target.id, ConstraintSet.START)<br>        applyTo(parent as ConstraintLayout)<br>    }<br>}</pre><p>This functions can also be called like this:</p><pre>private fun moveNameBelowHello(){<br>        with(binding) {<br>            textName startToStartOf root<br>            textName topToBottomOf textHello<br>            textName.disconnectBottom()<br>        }<br>}</pre><p>Why??? Because,</p><blockquote>Functions marked as infix are called infix functions. They can be called using infix notation. The infix notation is a way of calling the function without ‘.’ and ‘()’. On the left side, you will place the receiver instance and on the right side, you will place the parameter.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Kpk7dW7bfrW5rEFb" /></figure><p>So now let’s wrap it up here, and check what’s I have added so far.</p><ol><li><strong>Set Constraint Connections: </strong>Ever wanted to connect one view to another, say, starting from the start of a view or ending at the end of another? These functions, like startToStartOf and endToEndOf, will be your new best friends.</li><li><strong>Disconnect Connections: </strong>Sometimes, you need to sever the connection between views. With these KTX Functions, it’s as easy as pie.</li><li><strong>Set Margins: </strong>Adjusting margins for views is a common task in UI design. These functions streamline the process and keep your layout code neat.</li><li><strong>What’s in Store for the Future </strong>(Coming Soon): I’m not stopping here. I have plans to add even more functions to make your life as an Android developer even easier. Stay tuned for updates.</li></ol><blockquote><strong>Also don’t forget that Constraints and Ratio works only for the childs inside ConstraintLayout</strong></blockquote><p>Want to dive deeper into this? You can check out the code and more details on my GitHub profile. Here’s the <a href="https://gist.github.com/Meet-Miyani/38c9a0c8b09b5f423a183f4c350b983e#file-constraintktx"><strong>link</strong></a>.</p><p>So there you have it, a handy set of Kotlin Extension Functions that simplifies ConstraintLayout tasks for Android developers. Say goodbye to puzzling syntax and hello to a more efficient and enjoyable UI development experience.</p><p><strong><em>Happy coding, and may your UIs always be responsive!</em></strong></p><p>If you like the article, please support by Clapping 👏 , Saving and Sharing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*QIq454Kug5y6dkHx" /></figure><p><strong>Github Gist:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d39e2c95bc4bd81f0452c4e015a69ea/href">https://medium.com/media/0d39e2c95bc4bd81f0452c4e015a69ea/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91adf32e80f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>