<?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 Boobalan Munusamy on Medium]]></title>
        <description><![CDATA[Stories by Boobalan Munusamy on Medium]]></description>
        <link>https://medium.com/@boobalaninfo?source=rss-7a32b6599f65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AOSxeLPMbs5qNz-hhN1LPQ.jpeg</url>
            <title>Stories by Boobalan Munusamy on Medium</title>
            <link>https://medium.com/@boobalaninfo?source=rss-7a32b6599f65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:32:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@boobalaninfo/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[SwiftImport Migration in Kotlin Multiplatform (KMP): Import Swift Packages Directly into Kotlin ]]></title>
            <link>https://medium.com/@boobalaninfo/swiftimport-migration-in-kotlin-multiplatform-kmp-import-swift-packages-directly-into-kotlin-17d870e0656f?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/17d870e0656f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlinandroid]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kmp]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 13:54:22 GMT</pubDate>
            <atom:updated>2026-03-19T17:46:10.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3OMhEPxyfGXR5WZHerAGQ.png" /></figure><p>One of the long-standing wishes in the <strong>Kotlin Multiplatform (KMP)</strong> ecosystem has been the ability to directly use <strong>Swift Package Manager (SPM) libraries</strong> from Kotlin. Until recently, developers often had to create wrappers in Swift or rely on <strong>CocoaPods</strong> integrations.</p><p>With the introduction of <strong>Swift Package import support</strong>, this workflow becomes significantly easier.</p><p>In this article, I’ll share my experience migrating to this new feature and the challenges I encountered while integrating a real-world Swift library.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FG1o0Gc8dQ4E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DG1o0Gc8dQ4E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FG1o0Gc8dQ4E%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43dabd6d794a97587703134fd4639914/href">https://medium.com/media/43dabd6d794a97587703134fd4639914/href</a></iframe><h3>Why SwiftImport is Exciting for KMP Developers</h3><p>The new Swift import support allows Kotlin code to directly access libraries distributed through <strong>Swift Package Manager</strong>.</p><p><strong>Official documentation:<br></strong><a href="https://kotlinlang.org/docs/multiplatform/multiplatform-spm-import.html#configure-build-file">https://kotlinlang.org/docs/multiplatform/multiplatform-spm-import.html#configure-build-file</a></p><p>This is huge because it eliminates the need to:</p><ul><li>Write Swift wrappers</li><li>Maintain bridging layers</li><li>Depend on CocoaPods for every Swift dependency</li></ul><p>Instead, we can consume Swift libraries <strong>directly in Kotlin</strong>.</p><h3>My Real Use Case</h3><p>I’m currently migrating my <strong>Digital Diary app</strong> to Kotlin Multiplatform.</p><p>You can download the Android version here:<br><a href="https://play.google.com/store/apps/details?id=com.bob.offlinediary">https://play.google.com/store/apps/details?id=com.bob.offlinediary</a></p><p>For the iOS version, I wanted to integrate the Swift library:</p><p><strong>ZipArchive</strong><br><a href="https://github.com/ZipArchive/ZipArchive">https://github.com/ZipArchive/ZipArchive</a></p><p>This library is extremely useful for handling <strong>zip compression and extraction</strong> using secured password, which I use for <strong>backup and restore features</strong> in the diary app.</p><p>Previously, integrating this library from Kotlin was complicated.</p><p>With <strong>SwiftImport</strong>, the process becomes much simpler.</p><h3>Following the Official Sample</h3><p>To integrate the Swift package, I followed the official sample project provided by JetBrains:</p><p><a href="https://github.com/Kotlin/kmp-with-cocoapods-compose-sample/tree/spm_import">https://github.com/Kotlin/kmp-with-cocoapods-compose-sample/tree/spm_import</a></p><p>The setup process involved:</p><ol><li>Configuring the Swift package import in the <strong>Gradle build file</strong></li><li>Syncing the project</li><li>Letting the Kotlin build system generate the required Swift package files</li></ol><p>During this process, Kotlin generates a file at:</p><pre>build/kotlin/swiftImport/Package.swift</pre><p>This file defines the Swift package configuration required for the import.</p><h3>The Issue I Encountered</h3><p>While building the project using <strong>Xcode 15.2 on macOS 13</strong>, I encountered a <strong>compilation error</strong>.</p><p>After investigating, I discovered that the generated file:</p><pre>build/kotlin/swiftImport/Package.swift</pre><p>contained <strong>syntax issues</strong>, specifically:</p><ul><li>Incorrect commas in the package definition</li><li>Errors in the exact and package lines</li></ul><p>These syntax issues caused Swift Package Manager to fail during compilation.</p><p>From my observation, this appears to be an <strong>issue in the Kotlin compiler’s generated Swift package configuration</strong>.</p><pre>/Users/apple/AndroidStudioProjects/digitaldiary/ZipArchive/build/kotlin/swiftImport/Package.swift:19:5: error: unexpected &#39;,&#39; separator<br>    )<br>    ^<br>/Users/apple/AndroidStudioProjects/digitaldiary/ZipArchive/build/kotlin/swiftImport/Package.swift:28:9: error: unexpected &#39;,&#39; separator<br>        )<br>        ^<br><br>2026-03-19 06:11:40.646 xcodebuild[56271:370717] [MT] DVTAssertions: Warning in IDEFrameworks/IDEFoundation/Execution/RunContextManager/IDERunContextManager.m:848<br>Details:  Error deleting scheme: Cannot modify data because the process disallows saving.<br>Object:   &lt;IDERunContextManager: 0x600002c3fba0&gt;<br>Method:   -deleteRunContexts:completionQueue:completionBlock:<br>Thread:   &lt;_NSMainThread: 0x600000b043c0&gt;{number = 1, name = main}<br>Pl</pre><h3>Temporary Workaround</h3><p>To fix the issue, I manually corrected the generated Package.swift file.</p><p>However, there was another problem.</p><p>Every time I ran <strong>Gradle sync</strong>, the file was <strong>automatically regenerated</strong>, overwriting my fixes.</p><p>To work around this, I created a <strong>custom Gradle task</strong> that restores the corrected Package.swift file whenever the build runs.</p><pre>// build.gradle.kts<br><br>kotlin {<br>      // Post-processing to fix generated Package.swift syntax errors<br>    tasks.configureEach {<br>        if (name.contains(&quot;fetchSyntheticImportProjectPackages&quot;, ignoreCase = true) ||<br>            name.contains(&quot;generateSyntheticLinkageSwiftPMImportProject&quot;, ignoreCase = true)) {<br>    <br>            doLast {<br>                val manifest = project.layout.buildDirectory.file(&quot;kotlin/swiftImport/Package.swift&quot;).get().asFile<br>                if (manifest.exists()) {<br>                    val content = manifest.readText()<br>                    // Fix for trailing comma before closing parenthesis or bracket<br>                    val fixedContent = content<br>                        .replace(&quot;,\\s*\\)&quot;.toRegex(), &quot;\n    )&quot;)<br>                        .replace(&quot;,\\s*\\]&quot;.toRegex(), &quot;\n    ]&quot;)<br>    <br>                    if (content != fixedContent) {<br>                        manifest.writeText(fixedContent)<br>                        logger.lifecycle(&quot;Successfully fixed trailing commas in: ${manifest.absolutePath}&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This approach allows the project to compile successfully while still using the Swift package import feature.</p><h3>Recommendation for JetBrains</h3><p>This feature is extremely promising and opens up powerful possibilities for Kotlin Multiplatform developers.</p><p>However, the generated <strong>Package.swift</strong> file needs to be corrected in the Kotlin compiler to avoid these syntax issues.</p><p>Hopefully, JetBrains will address this in an upcoming release so developers can use <strong>Swift Package imports seamlessly without manual fixes</strong>.</p><h3>Final Thoughts</h3><p>Despite the issue, I’m very excited about this new capability.</p><p>Being able to <strong>directly access third-party Swift libraries from Kotlin</strong> will dramatically improve the developer experience when building <strong>Kotlin Multiplatform applications for iOS</strong>.</p><p>Once this feature becomes stable, it will remove a lot of interoperability friction between Kotlin and Swift.</p><p>For developers migrating existing apps to <strong>Kotlin Multiplatform</strong>, this is a feature worth exploring.</p><p>Follow my youtube channel : <a href="https://www.youtube.com/@piappstudio">https://www.youtube.com/@piappstudio</a><br>Follow my linked in profile: <a href="https://www.linkedin.com/in/boobalaninfo/">https://www.linkedin.com/in/boobalaninfo/</a><br>Follow my github KMP works:<a href="https://github.com/piappstudio/">https://github.com/piappstudio/</a><br>Follow my all my articles: <a href="https://piappstudio.com/category/mobile/">https://piappstudio.com/category/mobile/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17d870e0656f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Navigation 3: The Hidden Trap of State Loss (and How to Fix It)]]></title>
            <link>https://medium.com/@boobalaninfo/jetpack-compose-navigation-3-the-hidden-trap-of-state-loss-and-how-to-fix-it-d3f3637fc535?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f3637fc535</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 15:57:21 GMT</pubDate>
            <atom:updated>2026-02-21T15:59:00.815Z</atom:updated>
            <content:encoded><![CDATA[<p>The Frustration of “Fresh” Tabs Imagine this: Your user spends time writing a detailed diary entry or scrolling through a long list of reminders. They switch to the Settings tab for a second, come back, and — poof — the screen has reloaded, the scroll position is lost, and the ViewModel has been completely reset.<br>In modern Compose navigation (especially when using custom backstack implementations like Navigation3), this is a common architectu ral hurdle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkSzqLnUmIkfihJHfhDyLw.png" /><figcaption>Diary Images</figcaption></figure><h3>The Root Cause: Why removeAt is a ViewModel Killer</h3><p>Most developers implement “Single Top” navigation by searching for the target route in the backstack. If found, they remove it from its current position and add it back to the top:</p><pre>// THE BUGGY APPROACH<br>if (existingIndex != -1) {<br>    removeAt(existingIndex) // ViewModel is destroyed HERE!<br>}<br>add(route) // A brand-new ViewModel is created HEREkotl</pre><p>The Lifecycle Secret: In Compose Navigation, the moment a route is removed from the NavBackStack, even if only for a few milliseconds before being re-added, the navigation system assumes the screen is gone forever. It clears the ViewModelStore, effectively killing your state.</p><h3>Approach 1: Smart In-Place Shifting (The “Move-to-Top” Logic)</h3><p>This is the solution we implemented for DigitalDiary. Instead of removing the element, we shift the array in-place. This ensures the route never leaves the list, so the lifecycle remains continuous.<br>The Implementation</p><pre>fun NavBackStack&lt;NavKey&gt;.navigateSingleTop(route: NavKey) {<br>    val existingIndex = indexOf(route)<br>    if (existingIndex == -1) {<br>        add(route) // New tab} else if (existingIndex != size - 1) {<br>        // SMART SHIFT: Move the target to the top without removal<br>        val targetRoute = this[existingIndex]<br>        for (i in existingIndex until size - 1) {<br>            this[i] = this[i + 1]<br>        }<br>        this[size - 1] = targetRoute<br>    }<br>}</pre><h4>Pros:</h4><blockquote>Persistent ViewModels: The ViewModel instance is preserved because the entry never “died.”<br>Lightweight: Uses a single NavBackStack and a single NavDisplay.<br>Simple Back-Handling: Pressing “Back” naturally traverses the history of tabs visited.</blockquote><h4>Cons:</h4><blockquote>Root-Only Persistence: Best for flat navigation. If you are deep in a detail screen, switching tabs and coming back will bring the Root dashboard to the top, potentially losing the nested detail screen.</blockquote><h3>Approach 2: Multiple Navigation Stacks (The “Multi-Backstack” Pattern)</h3><p>For complex apps, you might create a separate NavBackStack for every single tab. In this setup, instead of moving routes within one stack, you “swap” which stack is currently visible.<br>The Implementation Concept</p><pre>// Inside your BottomNavGraph<br>val diaryStack = rememberNavBackStack(config, PiRoute.Diary)<br>val reminderStack = rememberNavBackStack(config, PiRoute.Reminder)<br><br>var activeTab by remember { mutableStateOf(Tab.Diary) }<br><br>Scaffold(<br>    bottomBar = { /* Switch activeTab */ }<br>) {<br>    // Keep both stacks alive in the UI tree, but only show one<br>    Box {<br>        if (activeTab == Tab.Diary) NavDisplay(diaryStack)<br>        if (activeTab == Tab.Reminder) NavDisplay(reminderStack)<br>    }<br>}</pre><h4>Pros:</h4><blockquote>Deep State Retention: If you are 5 screens deep in the “Diary” tab, switch to “Reminders,” and come back, you are still 5 screens deep.<br>Industry Standard: This is how major apps like YouTube or Spotify function.</blockquote><h4>Cons:</h4><blockquote>High Complexity: You must manually manage saving/restoring 3–5 different stacks.<br>Memory Usage: Multiple ViewModels and UI states are kept in memory simultaneously.</blockquote><h4>The Decision Matrix: Which One Should You Use?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*U7Zg055bzVAVnvKCVmsIqA.png" /></figure><h3>Final Verdict</h3><p>For DigitalDiary, we chose Approach 1 (Smart Shifting). It solves the primary complaint — losing dashboard state — without the heavy architectural burden of managing multiple parallel backstacks.</p><p>By manipulating the list in-place, we’ve ensured that the “Diary” and “Reminder” ViewModels stay alive as long as the user is in the bottom-bar section of the app. It’s an elegant “hack” that respects the Compose Lifecycle while providing a 10/10 user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f3637fc535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ A Complete Introduction to Android App Testing: JUnit, MockK, Robolectric, Espresso & WireMock]]></title>
            <link>https://medium.com/@boobalaninfo/a-complete-introduction-to-android-app-testing-junit-mockk-robolectric-espresso-wiremock-2723ca07796b?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/2723ca07796b</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[roboelectric]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[instrumentation]]></category>
            <category><![CDATA[wiremock]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 05:46:41 GMT</pubDate>
            <atom:updated>2025-06-30T03:07:59.100Z</atom:updated>
            <content:encoded><![CDATA[<p>In the modern Android development lifecycle, writing reliable tests isn’t an optional step — it’s essential. As apps grow in complexity, the cost of undetected bugs multiplies. Automated tests help catch issues early, facilitate safe refactoring, and allow for confident continuous integration and delivery (CI/CD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gvbkRB-WReOOGX9B" /><figcaption>Photo by <a href="https://unsplash.com/@uxindo?utm_source=medium&amp;utm_medium=referral">UX Indonesia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I’ll walk you through the key types of testing in Android development, including:</p><ul><li><strong>Unit testing with JUnit and MockK</strong></li><li><strong>Robolectric for local Android component tests</strong></li><li><strong>Instrumentation testing with Espresso</strong></li><li><strong>API mocking using WireMock</strong></li></ul><p>We’ll cover both the concepts and working code snippets for each. If you’re new to Android testing or want to level up your test strategy, this guide is for you.</p><h3>📌 Why Android App Testing Matters</h3><p>Testing ensures:</p><ul><li>Bugs are caught early in development.</li><li>The app works as expected in different scenarios.</li><li>You can safely refactor code without fear.</li><li>CI/CD pipelines can automatically verify your builds.</li></ul><p>Automating your tests reduces manual effort and boosts confidence during releases.</p><h3>📑 Types of Testing in Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puaKx2LDE7SZ24L8RDrrHg.png" /></figure><h3>1️⃣ Unit Testing with JUnit</h3><p><strong>JUnit</strong> is the standard Java testing framework for unit tests. In Android, you can use JUnit to test plain Kotlin/Java classes that don’t depend on Android SDK.</p><p>✅ <strong>Example:</strong></p><pre>class Calculator {<br>    fun add(a: Int, b: Int) = a + b<br>}</pre><pre>class CalculatorTest {<br>    @Test<br>    fun addition_isCorrect() {<br>        val calc = Calculator()<br>        assertEquals(5, calc.add(2, 3))<br>    }<br>}</pre><p>👉 These tests are fast because they run on the local JVM without launching an emulator.</p><h3>2️⃣ Unit Testing with MockK</h3><p><strong>MockK</strong> is a powerful Kotlin mocking library. It allows you to mock interfaces, classes, and even final classes or objects — making it ideal for Android apps.</p><p>✅ <strong>Example:</strong></p><pre>interface UserApi {<br>    fun getUser(): User<br>}</pre><pre>class UserRepo(private val api: UserApi) {<br>    fun fetchUserName() = api.getUser().name<br>}<br>class UserRepoTest {<br>    @Test<br>    fun `should return user name`() {<br>        val api = mockk&lt;UserApi&gt;()<br>        every { api.getUser() } returns User(&quot;Boobalan&quot;)<br>        val repo = UserRepo(api)<br>        assertEquals(&quot;Boobalan&quot;, repo.fetchUserName())<br>    }<br>}</pre><p>👉 This lets you test your business logic in isolation by mocking dependencies.</p><h3>3️⃣ Robolectric Testing</h3><p><strong>Robolectric</strong> allows Android UI components like Activity, Fragment, and View to run directly on the JVM without an emulator. It mimics the Android framework so you can test view interactions and lifecycle methods locally.</p><p>✅ <strong>Example:</strong></p><pre>@RunWith(RobolectricTestRunner::class)<br>class MainActivityTest {<br>    @Test<br>    fun buttonClick_shouldUpdateText() {<br>        val activity = Robolectric.buildActivity(MainActivity::class.java).create().get()<br>        activity.findViewById&lt;Button&gt;(R.id.btnClick).performClick()<br>        val textView = activity.findViewById&lt;TextView&gt;(R.id.tvOutput)<br>        assertEquals(&quot;Hello World&quot;, textView.text)<br>    }<br>}</pre><p>👉 This is perfect for faster UI logic tests without the overhead of a real device.</p><h3>4️⃣ Robolectric with MockK</h3><p>You can combine <strong>Robolectric</strong> and <strong>MockK</strong> to test Android components while mocking their dependencies.<br> For example, mock a ViewModel or Repository inside a Fragment and simulate UI actions.</p><p>✅ <strong>Concept:</strong></p><ul><li>Mock dependencies using MockK</li><li>Inject mocks into your activity/fragment</li><li>Use Robolectric to simulate Android lifecycle and UI actions</li></ul><p>This pattern is useful for <strong>MVVM architecture testing</strong>.</p><h3>5️⃣ Instrumentation Testing with Espresso</h3><p><strong>Espresso</strong> is Android’s official UI testing framework. It runs on real devices or emulators and interacts with your app like a real user: clicking buttons, entering text, and asserting view states.</p><p>✅ <strong>Example:</strong></p><pre>@Test<br>fun buttonClick_displaysText() {<br>    onView(withId(R.id.btnClick)).perform(click())<br>    onView(withId(R.id.tvOutput)).check(matches(withText(&quot;Hello&quot;)))<br>}</pre><p>👉 Ideal for end-to-end user flow validation.</p><h3>6️⃣ WireMock for API Mocking</h3><p><strong>WireMock</strong> lets you mock HTTP APIs during tests by simulating endpoints and their responses. This is extremely useful in <strong>Instrumentation</strong> or <strong>Integration tests</strong> when real APIs aren’t available or for simulating various server scenarios (like success, error, timeout).</p><p>✅ <strong>Typical Usage:</strong></p><ul><li>Start a WireMock server</li><li>Mock specific API routes with predefined JSON responses</li><li>Point your app’s Retrofit/HTTP client to the WireMock server during tests</li></ul><p>✅ <strong>Example:</strong></p><pre>WireMock.stubFor(get(urlEqualTo(&quot;/users&quot;))<br>    .willReturn(aResponse()<br>    .withStatus(200)<br>    .withBody(&quot;&quot;&quot;{&quot;name&quot;:&quot;Boobalan&quot;}&quot;&quot;&quot;)))</pre><p>Then, your Espresso or Instrumentation test can safely interact with this mocked API.</p><h3>📦 Tools &amp; Libraries:</h3><ul><li>JUnit</li><li>MockK</li><li>Robolectric</li><li>Espresso</li><li>WireMock</li><li>AndroidX Test</li></ul><h3>📌 Final Thoughts</h3><p>Having a well-balanced Android test strategy ensures:</p><ul><li>Stable, maintainable code</li><li>Faster bug fixes</li><li>Safer refactoring</li><li>Smooth CI/CD integrations</li></ul><p>Start with <strong>Unit tests</strong>, build up with <strong>Robolectric</strong> for local UI logic, and use <strong>Espresso</strong> for real UI flows. Add <strong>WireMock</strong> when APIs are involved to simulate different scenarios effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2723ca07796b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Multiplatform (KMM) Subscriptions: How to Implement In-App Subscriptions for Android and iOS]]></title>
            <link>https://medium.com/@boobalaninfo/kotlin-multiplatform-kmm-subscriptions-how-to-implement-in-app-subscriptions-for-android-and-ios-4cd18edfbe49?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd18edfbe49</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 23:23:37 GMT</pubDate>
            <atom:updated>2025-04-08T23:23:37.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tY4Vl0XQadq3eUkf" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we will walk through how to implement <strong>in-app subscriptions</strong> in a <strong>Kotlin Multiplatform Mobile (KMM)</strong> project, supporting both Android and iOS platforms using <strong>Google Play Billing 7.1.1</strong> and <strong>StoreKit</strong> respectively.</p><p>Video Playlist</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fmbt19of8sMI%3Flist%3DPL8u30_s78ZuFgDgThYIIWwX9AdPI3fjm-&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dmbt19of8sMI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fmbt19of8sMI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8b06e8db4bf1f3218545b93a96ae21/href">https://medium.com/media/be8b06e8db4bf1f3218545b93a96ae21/href</a></iframe><h3>✨ What We’ll Build</h3><ul><li>Unified subscription handling using KMM’s expect/actual pattern.</li><li>Billing implementation for Android using Google Play Billing 7.1.1.</li><li>Billing implementation for iOS using StoreKit and SKPaymentQueue.</li><li>A shared interface to check whether the user has an active subscription.</li></ul><h3>1. Define Shared Expect Class (commonMain)</h3><pre>expect class SubscriptionManager() {<br>    fun purchaseSubscription(callback: (Boolean) -&gt; Unit)<br>    fun isUserSubscribed(callback: (Boolean) -&gt; Unit)<br>    fun manageSubscription()<br>}</pre><h3>2. Android Implementation (androidMain)</h3><h3>Dependencies (build.gradle.kts)</h3><pre>dependencies {<br>    implementation(&quot;com.android.billingclient:billing-ktx:7.1.1&quot;)<br>}</pre><h3>BillingHelper for Android</h3><p>Kotlin helper file to handle subscrptions mechanism</p><p>BillingHelper.kt</p><pre>package iap<br><br>import android.app.Activity<br>import android.content.Context<br>import android.util.Log<br>import com.android.billingclient.api.AcknowledgePurchaseParams<br>import com.android.billingclient.api.BillingClient<br>import com.android.billingclient.api.BillingClientStateListener<br>import com.android.billingclient.api.BillingFlowParams<br>import com.android.billingclient.api.BillingResult<br>import com.android.billingclient.api.PendingPurchasesParams<br>import com.android.billingclient.api.Purchase<br>import com.android.billingclient.api.QueryProductDetailsParams<br>import com.android.billingclient.api.QueryPurchasesParams<br><br><br>class BillingHelper(private val context: Context) {<br><br>    val BIGG_BOSS_PREMIUM =&quot;premium_subscription&quot;<br>    val TAG = BillingHelper::class.simpleName<br>    var purchaseCallback:((isSuccess:Boolean)-&gt;Unit)? = null<br><br><br>    var params: PendingPurchasesParams = PendingPurchasesParams.newBuilder()<br>        .enableOneTimeProducts()<br>        .enablePrepaidPlans()<br>        .build()<br><br>    private var billingClient: BillingClient<br><br>    init {<br>        billingClient = BillingClient.newBuilder(context)<br>            .enablePendingPurchases(params)<br>            .setListener { billingResult, purchases -&gt;<br>                Log.d(&quot;enablePendingPurchases&quot;, &quot;BillingClient creation result : ${billingResult.responseCode}&quot;)<br>                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK &amp;&amp; purchases != null) {<br>                    handlePurchase(purchases)<br>                }<br>            }.build()<br>    }<br><br>    private fun connectPlayStore(callback: (isConnected:Boolean) -&gt; Unit) {<br>        if (billingClient.isReady) {<br>            callback.invoke(true)<br>        } else {<br>            billingClient.startConnection(object : BillingClientStateListener {<br>                override fun onBillingSetupFinished(billingResult: BillingResult) {<br>                    Log.d(TAG, &quot;startConnection onBillingSetupFinished&quot;)<br>                    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>                        // BillingClient is ready<br>                        Log.d(TAG, &quot;BillingClient is ready&quot;)<br>                        callback.invoke(true)<br>                    }<br>                }<br><br>                override fun onBillingServiceDisconnected() {<br>                    Log.d(TAG, &quot;startConnection onBillingServiceDisconnected&quot;)<br>                }<br>            })<br>        }<br>    }<br><br>    fun checkSubscriptionStatus(callback: (Boolean) -&gt; Unit) {<br>        Log.d(TAG, &quot;checkSubscriptionStatus&quot;)<br>        connectPlayStore {<br>            val params = QueryPurchasesParams.newBuilder()<br>                .setProductType(BillingClient.ProductType.SUBS)<br>                .build()<br><br>            billingClient.queryPurchasesAsync(params) { billingResult, purchases -&gt;<br>                Log.d(TAG, &quot;queryPurchasesAsync callback: ${billingResult.responseCode}, ${purchases.size}&quot;)<br>                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>                    val isSubscribed = purchases.any { it.products.contains(BIGG_BOSS_PREMIUM) }<br>                    callback(isSubscribed)<br>                } else {<br>                    callback(false)<br>                }<br>            }<br>        }<br><br>    }<br><br><br>    fun purchaseSubscription(activity: Activity, callback: (Boolean) -&gt; Unit) {<br>        val params = QueryProductDetailsParams.newBuilder()<br>            .setProductList(<br>                listOf(<br>                    QueryProductDetailsParams.Product.newBuilder()<br>                        .setProductId(BIGG_BOSS_PREMIUM)<br>                        .setProductType(BillingClient.ProductType.SUBS)<br>                        .build()<br>                )<br>            )<br>            .build()<br><br>        billingClient.queryProductDetailsAsync(params) { billingResult, productDetailsList -&gt;<br>            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK &amp;&amp; productDetailsList.isNotEmpty()) {<br>                val productDetails = productDetailsList.first()<br>                val offerToken = productDetails.subscriptionOfferDetails?.first()?.offerToken<br>                    ?: return@queryProductDetailsAsync<br><br>                val billingParams = BillingFlowParams.newBuilder()<br>                    .setProductDetailsParamsList(<br>                        listOf(<br>                            BillingFlowParams.ProductDetailsParams.newBuilder()<br>                                .setProductDetails(productDetails)<br>                                .setOfferToken(offerToken)<br>                                .build()<br>                        )<br>                    )<br>                    .build()<br><br>                purchaseCallback = callback<br>                billingClient.launchBillingFlow(activity, billingParams)<br>            }<br>        }<br>    }<br><br>    private fun handlePurchase(purchases: List&lt;Purchase&gt;) {<br>        for (purchase in purchases) {<br>            if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {<br>                // Grant subscription benefits<br>                Log.d(&quot;BillingManager&quot;, &quot;Subscription is active: ${purchase.products}&quot;)<br>                acknowledgePurchase(purchase)<br>                purchaseCallback?.invoke(true)<br>                purchaseCallback = null<br>            }<br>        }<br>    }<br><br>    private fun acknowledgePurchase(purchase: Purchase) {<br>        if (!purchase.isAcknowledged) {<br>            val params = AcknowledgePurchaseParams.newBuilder()<br>                .setPurchaseToken(purchase.purchaseToken)<br>                .build()<br><br>            billingClient.acknowledgePurchase(params) { billingResult -&gt;<br>                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {<br>                    Log.d(&quot;BillingManager&quot;, &quot;Purchase acknowledged&quot;)<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><h3>SubscriptionManager for Android</h3><p>SubscriptionManager.android.kt</p><pre>package iap<br><br>import android.app.Activity<br>import ui.native.LinkLauncher<br>import ui.native.PiShared<br><br>actual class SubscriptionManager {<br><br>    private val billingHelper = BillingHelper(PiShared.applicationContext!!)<br>    actual fun purchaseSubscription(callback: (Boolean) -&gt; Unit) {<br>        (PiShared.applicationContext as? Activity)?.let {<br>            billingHelper.purchaseSubscription(it, callback)<br>        }<br>    }<br>    actual fun isUserSubscribed(callback: (Boolean) -&gt; Unit) {<br>        billingHelper.checkSubscriptionStatus (callback)<br>    }<br><br>    actual fun manageSubscription() {<br>        LinkLauncher().openLink(&quot;https://play.google.com/store/account/subscriptions&quot;)<br>    }<br><br><br>}</pre><h3>3. iOS Implementation (iOSApp)</h3><p>Swift code that handle iOS native implementation for Subscription handling. Add <em>SubscriptionManager</em>.<em>swift</em> in the following folder</p><p>iosApp/iOSApp/Subscription</p><pre>//<br>//  SubscriptionManager.swift<br>//  iosApp<br>//<br>//  Created by Apple on 4/2/25.<br>//  Copyright © 2025 orgName. All rights reserved.<br>//<br><br>import Foundation<br>import StoreKit<br><br>@objc public class SubscriptionManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {<br>    let PRODUCT_ID = &quot;ios_subscription&quot;<br>    @objc public static let shared = SubscriptionManager()<br>    var products: [SKProduct] = []<br>    <br>    var purchaseCallBack:((Bool)-&gt;Void)? = nil<br>    <br>    override init() {<br>        super.init()<br>        SKPaymentQueue.default().add(self)<br>    }<br>    <br>    @objc public func fetchSubscriptions() {<br>        let request = SKProductsRequest(productIdentifiers: [PRODUCT_ID])<br>        request.delegate = self<br>        request.start()<br>    }<br>    <br>    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {<br>        self.products = response.products<br>        print(&quot;productsRequest is called: \(self.products)&quot;)<br>        for product in products {<br>            print(product.productIdentifier)<br>        }<br>    }<br>    <br>    @objc public func purchaseSubscription(productId: String, callback:(@escaping (Bool)-&gt; Void)) {<br>        <br>        guard let product = products.first(where: { $0.productIdentifier == productId }) else { return }<br>        let payment = SKPayment(product: product)<br>        purchaseCallBack = callback<br>        SKPaymentQueue.default().add(payment)<br>    }<br>    <br>    @objc public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {<br>        for transaction in transactions {<br>            switch transaction.transactionState {<br>            case .purchased:<br>                unlockContent(productId: transaction.payment.productIdentifier)<br>                <br>                SKPaymentQueue.default().finishTransaction(transaction)<br>            case .failed:<br>                SKPaymentQueue.default().finishTransaction(transaction)<br>            default:<br>                break<br>            }<br>        }<br>    }<br>    <br>    private func unlockContent(productId: String) {<br>        purchaseCallBack?(true)<br>        UserDefaults.standard.set(true, forKey: productId)<br>    }<br>    <br>    @objc public func isSubscribed(productId: String) -&gt; Bool {<br>        return UserDefaults.standard.bool(forKey: productId)<br>    }<br>}</pre><h3>Expose swift code to Kotlin using swift-klib</h3><p>Swift-Klib gradle plugin provides easy way to include your Swift source files in your Kotlin Multiplatform Mobile shared module and access them in Kotlin via cinterop for iOS targets.</p><p><a href="https://github.com/ttypic/swift-klib-plugin">GitHub - ttypic/swift-klib-plugin: Gradle Plugin for injecting Swift code into Kotlin Multiplatform Mobile shared module</a></p><pre>[version]<br>swift-klib = &quot;0.6.4&quot;<br>[plugins]<br>swift-klib = { id = &quot;io.github.ttypic.swiftklib&quot;, version.ref = &quot;swift-klib&quot;}<br></pre><p>shared/build.gradle.kts</p><pre>plugins {<br>    alias(libs.plugins.swift.klib)<br><br>}<br><br>kotlin {<br><br>  listOf(<br>        iosX64(),<br>        iosArm64(),<br>        iosSimulatorArm64()<br>    ).forEach { iosTarget -&gt;<br>        iosTarget.compilations {<br>            val main by getting {<br>                cinterops {<br>                    create(&quot;Subscription&quot;)<br>                }<br>            }<br>        }<br>    }<br>}<br><br><br>// ../iosApp/iosApp/Subscription is folder path where Subscription.swift<br><br>swiftklib {<br>    create(&quot;Subscription&quot;) {<br>        path = file(&quot;../iosApp/iosApp/Subscription&quot;)<br>         // Kotlin package name<br>        packageName(&quot;com.piappstudio.swift.subscription&quot;)<br>    }<br>}</pre><h3>iOS Implementation (iOSMain)</h3><p>Let’s access Swift function from Kotlin</p><p>SubscriptionManager.ios.kt</p><pre>package iap<br>import co.touchlab.kermit.Logger<br>import com.piappstudio.swift.subscription.SubscriptionManager<br>import kotlinx.cinterop.ExperimentalForeignApi<br>import model.PiGlobalInfo<br>import ui.native.LinkLauncher<br><br>@OptIn(ExperimentalForeignApi::class)<br>actual class SubscriptionManager  {<br><br>    val productId = &quot;tamil&quot;<br>     var subscriptionManager: SubscriptionManager = SubscriptionManager.shared()<br><br>    init {<br>        subscriptionManager.fetchSubscriptions()<br>    }<br><br>    actual fun purchaseSubscription(callback: (Boolean) -&gt; Unit) {<br>        Logger.d(tag = &quot;SubscriptionManager&quot;, messageString = &quot;purchaseSubscription&quot;)<br>        subscriptionManager.purchaseSubscriptionWithProductId(productId, callback = callback)<br>    }<br><br>    @OptIn(ExperimentalForeignApi::class)<br>    actual fun isUserSubscribed(callback: (Boolean) -&gt; Unit) {<br>        Logger.d(&quot;isUserSubscribed&quot;)<br>        val isSubscribed = subscriptionManager.isSubscribedWithProductId(productId)<br>        Logger.d(tag = &quot;SubscriptionManager&quot;,  messageString = &quot;isSubscribed: $isSubscribed&quot;)<br>        callback.invoke(isSubscribed)<br>    }<br><br>    actual fun manageSubscription() {<br>        LinkLauncher().openLink(&quot;https://apps.apple.com/account/subscriptions&quot;)<br>    }<br><br>}</pre><h3>4. Usage in Shared Code</h3><pre>private fun checkSubscription() {<br>    screenModelScope.launch (Dispatchers.IO)  {<br>        subscriptionManager.isUserSubscribed { isPremiumUser -&gt;<br>            Logger.d(&quot;Subscription Manager: $isPremiumUser&quot;)<br>            val premiumStatus = if (isPremiumUser) PremiumStatus.Subscribed else PremiumStatus.UnSubscribed<br>            piGlobalUtil.updateAppState(piGlobalUtil.appState.value.copy(premiumStatus = premiumStatus))<br>        }<br>    }<br>}</pre><pre>Button(onClick = {<br>                subscriptionManager.purchaseSubscription(callback)<br>            },<br>                modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors().copy(containerColor = PiColor.goldStar,<br>                    contentColor = MaterialTheme.colorScheme.onSurface)<br>            ) {<br>                Text(<br>                    &quot;GO PREMIUM FOR $0.99 / YEAR&quot;,<br>                    fontWeight = FontWeight.ExtraBold,<br>                    modifier = Modifier.padding(Dimens.space)<br>                )<br>            }</pre><pre>Button(onClick = {<br>                subscriptionManager.manageSubscription()<br>            },<br>                modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors().copy(containerColor = PiColor.goldStar,<br>                    contentColor = MaterialTheme.colorScheme.onSurface)<br>            ) {<br>                Text(<br>                    &quot;Manage Subscription&quot;,<br>                    fontWeight = FontWeight.ExtraBold,<br>                    modifier = Modifier.padding(Dimens.space)<br>                )<br>            }</pre><h3>🚀 Summary</h3><p>Now you have:</p><ul><li>A complete subscription flow for both Android and iOS in KMM.</li><li>Observer integration for iOS via StoreObserver.</li><li>Google Play Billing integration via version 7.1.1.</li></ul><p>Want to add <strong>restore purchase support</strong> or <strong>server-side receipt validation</strong>? Drop a comment or request a follow-up!</p><p>Reference:<a href="https://piappstudio.com/kotlin-multiplatform-kmm-subscriptions-how-to-implement-in-app-subscriptions-for-android-and-ios/">https://piappstudio.com/kotlin-multiplatform-kmm-subscriptions-how-to-implement-in-app-subscriptions-for-android-and-ios/</a></p><p>Happy coding ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd18edfbe49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Don’t Need a Server for UI Development — Yes, You Heard It Right!]]></title>
            <link>https://medium.com/@boobalaninfo/i-dont-need-a-server-for-ui-development-yes-you-heard-it-right-a6334b31a210?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6334b31a210</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[ui-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[wiremock]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 16:06:01 GMT</pubDate>
            <atom:updated>2024-06-17T15:47:05.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Don’t Need a Server for UI Development — Yes, You Heard It Right!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ss0hRUzxYjXCMBfHhosv1w.jpeg" /><figcaption>Pi App Studio image</figcaption></figure><p>In the world of UI development, many of us face various server-related impediments such as ongoing server development, deployment issues, server unavailability, and more. These challenges often slow down the development process. To overcome these obstacles, I’ve chosen to use WireMock, a powerful tool that allows developers to mock HTTP servers and create predictable, testable, and independent UI environments.</p><p>In this article, I’ll walk you through the process of setting up WireMock, configuring different scenarios, and validating an endpoint. You can find the initial WireMock templates in this</p><p><a href="https://github.com/piappstudio/WireMock/tree/main">GitHub - piappstudio/WireMock: This repository helps you to setup wiremock server for client side development. Please refer ReadMe for more details</a></p><p>Reference video is available here</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaJVQrCRTc4I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaJVQrCRTc4I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaJVQrCRTc4I%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bdb7a76862de9afa854690652f7c57/href">https://medium.com/media/23bdb7a76862de9afa854690652f7c57/href</a></iframe><h3>Why Use WireMock?</h3><p>WireMock helps eliminate server dependencies during development. By simulating server responses, you can develop and test your UI without waiting for the actual server to be ready or available. This approach ensures that you can cover all possible edge cases before integration, improving the reliability and robustness of your application.</p><h3>Setting Up WireMock</h3><p>Follow these steps to set up WireMock on your local machine:</p><p><strong>Clone the Repository:</strong></p><p>git clone <a href="https://github.com/piappstudio/WireMock.git">https://github.com/piappstudio/WireMock.git</a></p><p><strong>Run WireMock:</strong> Open the terminal and execute the following command to set up the local server:</p><pre>java -jar wiremock-standalone-3.6.0.jar --port 9191 --verbose --global-response-templating --jetty-header-buffer-size 16384</pre><p>This command starts the WireMock server on port 9191 with verbose logging and global response templating enabled.</p><h4>Folder Stucture</h4><ol><li>__file<br>The __files folder is used to store static files that can be served as part of the response for mocked requests. These files can include JSON, XML, or any other content that you might want to return as part of your mock server&#39;s response.</li><li>mappings<br>The __files folder is used to store static files that can be served as part of the response for mocked requests. These files can include JSON, XML, HTML, or any other content that you might want to return as part of your mock server&#39;s response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TFK4NOHTxIqMX8zOU1WFwg.png" /></figure><p>Let’s say you want to create a stub that returns a specific JSON response for a GET request to /v1/biggoss/shows.</p><pre>{<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;url&quot; : &quot;/v1/biggboss/shows&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    },<br>    &quot;bodyFileName&quot;: &quot;biggboss-shows-api/default.json&quot;<br>  }<br>}</pre><ul><li><strong>Request:</strong> Defines the structure of the incoming request.</li><li><strong>Response:</strong> Defines the structure of the response for the above request.</li></ul><h3>Validating the API</h3><p>To validate the /v1/biggboss/shows endpoint, follow these steps:</p><ol><li><strong>Open Postman:</strong> Import the WireMock-BiggBoss.postman_collection.json file into Postman.</li><li><strong>Invoke the Request:</strong> Send a request to the “Bigg Boss Shows” endpoint to receive the response.</li></ol><pre>{<br>  &quot;shows&quot;: [<br>    {<br>      &quot;title&quot;: &quot;BiggBoss Tamil Season 7&quot;,<br>      &quot;id&quot;: &quot;bbtamil7&quot;,<br>      &quot;host&quot;: &quot;Kamalahaasan&quot;,<br>      &quot;start_date&quot;: &quot;2023-10-01&quot;,<br>      &quot;end_date&quot;: &quot;2024-01-14&quot;,<br>      &quot;winner&quot;: &quot;Archana&quot;,<br>      &quot;runner&quot;: &quot;Manichandra&quot;,<br>      &quot;cash&quot;: &quot;Poornima (16L)&quot;,<br>      &quot;logo&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/images/shows/tamil/session7/logo.png&quot;,<br>      &quot;more_info&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/json/shows/tamil_session_7.json&quot;,<br>      &quot;trends&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/json/shows/tamil_session_7_trends.json&quot;,<br>      &quot;votes&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/json/shows/tamil/season7/votes.json&quot;<br>    }<br>  ],<br>  &quot;reviewers&quot;: [<br>    {<br>      &quot;channel_name&quot;: &quot;SBI Electroal Bond - 1 (Google Drive)&quot;,<br>      &quot;description&quot;: &quot;Download Electoral Bond Part-1 in Excel format for better analysis in Google Drive&quot;,<br>      &quot;url&quot;: &quot;https://docs.google.com/spreadsheets/d/17DJrN1orB93OTIYF6QMiFj1aZ9F2WZrA_D8zfjH56FE&quot;,<br>      &quot;image&quot;:&quot;https://i.ytimg.com/vi/z_OY38rDj9k/hq720.jpg&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;SBI Electroal Bond - 2 (Google Drive)&quot;,<br>      &quot;description&quot;: &quot;Download Electoral Bond Part-2 in Excel format for better analysis in Google Drive&quot;,<br>      &quot;url&quot;:&quot;https://docs.google.com/spreadsheets/d/1GQBoGkyqNd3HOWDaJc2ueOmDQpmYob74&quot;,<br>      &quot;image&quot;:&quot;https://i.ytimg.com/vi/z_OY38rDj9k/hq720.jpg&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;Bigg Boss Tamizh Review&quot;,<br>      &quot;description&quot;: &quot;BiggBoss Review, Critics, Troll &amp; Deep Analysis&quot;,<br>      &quot;url&quot;: &quot;https://www.youtube.com/@tamizhreview/videos&quot;,<br>      &quot;image&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/images/shows/tamil/session7/channels/tamizhreview.png&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;Pi App Studio&quot;,<br>      &quot;description&quot;: &quot;Free iOS &amp; Android development courses in Tamil&quot;,<br>      &quot;url&quot;: &quot;https://www.youtube.com/@piappstudio/videos&quot;,<br>      &quot;image&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/images/shows/tamil/session7/channels/piappstudio.png&quot;<br>    }<br>  ]<br>}</pre><p>Now, let’s dive into scenario based configurations.</p><h3>Understanding Basic Keywords in WireMock</h3><h4>Url/UrlPathPattern</h4><p>Defines the URL to be handled by WireMock.</p><h4>Priority</h4><p>Sets the priority of the configuration. If multiple configurations exist, the one with the highest priority (lowest number) is selected. The default value is 5, where 1 is the highest priority and Integer.MAX_VALUE (from Java) is the lowest priority</p><h4>ScenarioName</h4><ul><li><strong>Definition:</strong> A unique identifier for a group of related stubs that belong to the same scenario.</li><li><strong>Purpose:</strong> To connect multiple requests and responses, allowing for stateful behavior.</li><li><strong>Example:</strong> &quot;scenarioName&quot;: &quot;biggboss-show&quot;</li></ul><h4>newScenarioState</h4><ul><li><strong>Definition:</strong> The state that the scenario transitions to after the request is matched and the response is served.</li><li><strong>Purpose:</strong> Allows the scenario to move to a different state, enabling sequential stateful interactions.</li><li><strong>Example:</strong> &quot;newScenarioState&quot;: &quot;shows-only&quot;</li></ul><h4>requiredScenarioState</h4><ul><li><strong>Definition:</strong> Specifies the state that a scenario must be in for a particular stub to match the request.</li><li><strong>Purpose:</strong> Ensures that the stub only matches when the scenario is in a specified state.</li><li><strong>Example:</strong> &quot;requiredScenarioState&quot;: &quot;shows-only&quot;</li></ul><h3>Configure EMPTY scenario</h3><p>Create a new endpoint/scenario/shows/empty to trigger the “shows-empty” state</p><pre>{<br>  &quot;scenarioName&quot;: &quot;biggboss-show&quot;,<br>  &quot;newScenarioState&quot;: &quot;shows-empty&quot;,<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;POST&quot;,<br>    &quot;urlPathPattern&quot; : &quot;/scenario/shows/empty&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;body&quot;: &quot;Empty show scenario stated&quot;<br>  }<br>}<br></pre><p>This configuration is useful in a scenario where you want to simulate the behavior of an application that manages “Bigg Boss” shows. By posting to the endpoint /scenario/shows/empty, you transition the state of the scenario to &quot;shows-empty&quot;, which could influence how subsequent requests are handled.</p><p>Now, let’s detect this state and configure the response for /v1/biggboss/shows</p><pre>{<br>  &quot;scenarioName&quot;: &quot;biggboss-show&quot;,<br>  &quot;requiredScenarioState&quot;: &quot;shows-empty&quot;,<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;url&quot; : &quot;/v1/biggboss/shows&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    },<br>    &quot;bodyFileName&quot;: &quot;biggboss-shows-api/empty_shows.json&quot;<br>  }<br>}</pre><p>empty_shows.json</p><pre>{}</pre><p>Please note here, we are configuring empty_shows.json file for /v1/biggboss/shows api when requiredScenarioState: shows-empty</p><h4>Steps to exeucte</h4><ol><li>Start the mock server</li><li>Invoke /scenario/shows/empty to trigger “shows-empty” scenario</li><li>Call the client api /v1/biggboss/shows to receive empty json</li></ol><h3>Configure Reviewer ONLY scenario</h3><p>Create a new endpoint/scenario/shows/reviewers to trigger the shows-reviewers-only scenario</p><pre>{<br>  &quot;scenarioName&quot;: &quot;biggboss-show&quot;,<br>  &quot;newScenarioState&quot;: &quot;shows-reviewers-only&quot;,<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;POST&quot;,<br>    &quot;urlPathPattern&quot; : &quot;/scenario/shows/reviewers&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;body&quot;: &quot;Only reviewers scenario stated&quot;<br>  }<br>}</pre><p>Configure stub to match shows-reviewers-onlyscenario</p><pre>{<br>  &quot;scenarioName&quot;: &quot;biggboss-show&quot;,<br>  &quot;requiredScenarioState&quot;: &quot;shows-reviewers-only&quot;,<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;url&quot; : &quot;/v1/biggboss/shows&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    },<br>    &quot;bodyFileName&quot;: &quot;biggboss-shows-api/only_reviewers.json&quot;<br>  }<br>}</pre><p>only_reviewers.json</p><pre>{<br>  &quot;reviewers&quot;: [<br>    {<br>      &quot;channel_name&quot;: &quot;SBI Electroal Bond - 1 (Google Drive)&quot;,<br>      &quot;description&quot;: &quot;Download Electoral Bond Part-1 in Excel format for better analysis in Google Drive&quot;,<br>      &quot;url&quot;: &quot;https://docs.google.com/spreadsheets/d/17DJrN1orB93OTIYF6QMiFj1aZ9F2WZrA_D8zfjH56FE&quot;,<br>      &quot;image&quot;:&quot;https://i.ytimg.com/vi/z_OY38rDj9k/hq720.jpg&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;SBI Electroal Bond - 2 (Google Drive)&quot;,<br>      &quot;description&quot;: &quot;Download Electoral Bond Part-2 in Excel format for better analysis in Google Drive&quot;,<br>      &quot;url&quot;:&quot;https://docs.google.com/spreadsheets/d/1GQBoGkyqNd3HOWDaJc2ueOmDQpmYob74&quot;,<br>      &quot;image&quot;:&quot;https://i.ytimg.com/vi/z_OY38rDj9k/hq720.jpg&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;Bigg Boss Tamizh Review&quot;,<br>      &quot;description&quot;: &quot;BiggBoss Review, Critics, Troll &amp; Deep Analysis&quot;,<br>      &quot;url&quot;: &quot;https://www.youtube.com/@tamizhreview/videos&quot;,<br>      &quot;image&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/images/shows/tamil/session7/channels/tamizhreview.png&quot;<br>    },<br>    {<br>      &quot;channel_name&quot;: &quot;Pi App Studio&quot;,<br>      &quot;description&quot;: &quot;Free iOS &amp; Android development courses in Tamil&quot;,<br>      &quot;url&quot;: &quot;https://www.youtube.com/@piappstudio/videos&quot;,<br>      &quot;image&quot;: &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/images/shows/tamil/session7/channels/piappstudio.png&quot;<br>    }<br>  ]<br>}</pre><h4>Steps to exeucte</h4><ol><li>Start the mock server</li><li>Invoke /scenario/shows/reviewers to trigger “shows-reviewers-only” scenario</li><li>Call the client api /v1/biggboss/shows to receive reviewers ony json response.</li></ol><p>Likewise, we can configure “N” number of scenarios and respective client stubs.</p><h4>Handling Global Errors for All API</h4><p>Global errors such as 500, 503, and 404 can be handled using WireMock scenarios in a similar way to other endpoint-specific scenarios. Here’s how you can configure them:</p><ol><li><strong>Creating Error Scenarios:</strong></li></ol><ul><li><strong>500 Internal Server Error:</strong> server-down-error-started</li><li><strong>503 Service Unavailable:</strong> server-maintenance-error-started</li><li><strong>404 Not Found:</strong> server-api-not-found-error-started</li></ul><p>However, configuring client stubs for these global errors involves a few specific considerations:</p><ul><li><strong>Priority:</strong> Set &quot;priority&quot;: 1. By default, stub priority is 5, but setting it to 1 ensures this stub takes the highest priority when a request is made. WireMock will intercept every request, check for requiredScenarioState, and return the appropriate error response if the system state matches.</li><li><strong>urlPathPattern:</strong> Use &quot;/(.*)&quot;. This wildcard regex matches all endpoints, ensuring that the error response applies globally.</li></ul><pre>{<br>  &quot;priority&quot;: 1,<br>  &quot;scenarioName&quot;: &quot;general-server-error&quot;,<br>  &quot;requiredScenarioState&quot;: &quot;server-down-error-started&quot;,<br>  &quot;request&quot;: {<br>    &quot;urlPathPattern&quot; : &quot;/(.*)&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 500,<br>    &quot;body&quot;: &quot;Server is Down&quot;<br>  }<br>}</pre><h4>Steps to exeucte</h4><ol><li>Start the mock server</li><li>Invoke /scenario/trigger-server-down-error to start the “500 error” scenario</li><li>Call the client api /v1/biggboss/shows to receive 500 error response, in fact, the system through this error 500 error for all the api calls.</li><li>To reset all scenarios, invoke __admin/scenarios/reset</li></ol><h3>Conclusion</h3><p>Using WireMock for UI development is a game-changer. It allows you to work independently of server availability, ensuring that your development process is efficient and uninterrupted. By setting up different scenarios and validating your endpoints, you can build more reliable and robust applications.</p><p>Check out the <a href="https://github.com/piappstudio/WireMock">GitHub repository</a> &amp; <a href="https://youtu.be/aJVQrCRTc4I">subscribe my channel</a> for more details and templates to get started. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6334b31a210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Kotlin 1.9.x to 2.0.0]]></title>
            <link>https://medium.com/@boobalaninfo/migrating-kotlin-1-9-x-to-2-0-0-8d3d8ac82192?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d3d8ac82192</guid>
            <category><![CDATA[k2]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 00:06:43 GMT</pubDate>
            <atom:updated>2024-06-07T07:17:14.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin 2.0 introduces a host of impressive features, making it an enticing update for developers. However, <a href="https://developer.android.com/build/migrate-to-ksp">migrating from Kotlin 1.9.x to 2.0</a>.0 isn’t as straightforward as one might hope.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvkvlxE2bNF0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvkvlxE2bNF0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvkvlxE2bNF0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ce2ddd3f32f7aaa4a421e758aeac372/href">https://medium.com/media/9ce2ddd3f32f7aaa4a421e758aeac372/href</a></iframe><p>One significant change is that Kotlin 2.0 does not enable KAPT (Kotlin Annotation Processing Tool) by default, necessitating a migration from KAPT to KSP (Kotlin Symbol Processing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bOvg-I31uv_S_FO9" /><figcaption>Kotlin 2.0 KAPT compilation Error</figcaption></figure><h3>Migrating to Kotlin 2.0.0</h3><p>Follow <a href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-compiler.html#what-s-next">this document</a> to update the kotlin version &amp; it’s plugn</p><pre>[versions]<br>kotlin_version = &quot;2.0.0&quot;</pre><pre>[plugins]<br>compose-compiler = { id = &quot;org.jetbrains.kotlin.plugin.compose&quot;, version.ref = &quot;kotlin_version&quot; }</pre><p>Add the Gradle plugin to the root build.gradle.kts file:</p><pre>plugins {     // ...     alias(libs.plugins.compose.compiler) apply false }</pre><p>Apply the plugin to every module that uses Jetpack Compose:</p><pre>plugins {     // ...     alias(libs.plugins.compose.compiler) }</pre><h3>Troubleshooting Compilation Issues</h3><p>After migrating to KSP, you might encounter the following error during compilation in Android Studio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*La1en7JTczhXg8CKk-Hwig.png" /></figure><p>Let’s use Run with — — info option so that you could understand the cause behind it and the issue is</p><pre>ksp-1.9.0–1.0.12 is too old for kotlin-2.0.0. Please upgrade ksp or downgrade kotlin-gradle-plugin to 1.9.0.</pre><h3>Solution</h3><p>After updating to KSP version 2.0.0-1.0.22, recompile your project in Android Studio. The compilation should proceed successfully, indicating that your project is now running with Kotlin 2.0.</p><blockquote>Finally don’t foget to give a retirement to compose compiler by remove this kotlinCompilerExtensioinVersion and it’s version from catlog</blockquote><pre>composeOptions {<br>    // Remove this option, it doesn&#39;t needed anymore<br>    kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get()<br>}</pre><h3>Conclusion</h3><p>Migrating to Kotlin 2.0 involves several steps and careful attention to detail, particularly regarding the transition from KAPT to KSP. By following this guide, you should be able to navigate the migration process smoothly. Keep your dependencies updated, and make sure to test thoroughly to ensure compatibility and functionality. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d3d8ac82192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assessing Type Safe Navigation Compose in Android Development]]></title>
            <link>https://medium.com/@boobalaninfo/assessing-type-safe-navigation-compose-in-android-development-8bd09db244bb?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd09db244bb</guid>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Fri, 10 May 2024 23:37:46 GMT</pubDate>
            <atom:updated>2024-05-13T16:24:45.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAEQQaOp3HekyoWb36518g.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fdjs9UkUaen4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ddjs9UkUaen4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2856973b758cef8ff77031e1f819a041/href">https://medium.com/media/2856973b758cef8ff77031e1f819a041/href</a></iframe><h4>Project Setup</h4><p>As per the documentation, in libs.versions.toml</p><pre>[version]<br>navigationCompose = &quot;2.8.0-alpha08&quot;<br>kotlinSerializaton = &quot;1.6.3&quot;<br><br>[libraries]<br>androidx-navigation =  { group = &quot;androidx.navigation&quot;, name = &quot;navigation-compose&quot;, version.ref=&quot;navigationCompose&quot;}<br>kotlinx-serialization =  { group = &quot;org.jetbrains.kotlinx&quot;, name = &quot;kotlinx-serializati<br>on-json&quot;, version.ref = &quot;kotlinSerializaton&quot;}</pre><p>app’s build.gradle.kts</p><pre>plugins {<br>    alias(libs.plugins.android.application)<br>    alias(libs.plugins.jetbrains.kotlin.android)<br>    kotlin(&quot;plugin.serialization&quot;) version &quot;1.9.24&quot;<br>}<br><br>dependencies {<br>   implementation(libs.androidx.navigation)<br>   implementation(libs.kotlinx.serialization)<br>}</pre><p>Here, the OnBoardingScreen needs to know the current status of terms &amp; condition and isHelpShown value to understand the user’s preferences. OnBoardInfo is served by API and the same has been bound with graph.</p><pre>package com.piappstudio.piauth.data<br><br>import kotlinx.serialization.Serializable<br><br>@Serializable<br>data class OnBoardInfo(val isTermsAccepted:Boolean? = null,<br>                       val isHelpShown:Boolean? = false)</pre><pre>@Composable<br>fun SetupNavigation() {<br>    val navController = rememberNavController()<br><br>    NavHost(navController = navController, startDestination = Splash) {<br>        composable&lt;Splash&gt; {<br>            SplashScreen {<br>                navController.navigate(OnBoardInfo())<br>            }<br>        }<br>        composable&lt;OnBoardInfo&gt; {<br>            val onBoardInfo = it.toRoute&lt;OnBoardInfo&gt;()<br>            OnBoardingScreen(onBoardInfo)<br>        }<br>        composable&lt;Profile&gt; {<br>            LoginScreen()<br>        }<br><br>    }<br>}</pre><p>During execution, the system throws an exception as shown above.</p><h4>Int, boolean does not allow nullable values</h4><p>The realm of Android development is ever-evolving, with each new feature promising to revolutionize the way we build apps. Among these innovations, Type Safe Navigation Compose has garnered significant attention. Touted as a game-changer, it aims to streamline navigation and enhance type safety in Jetpack Compose applications. However, as developers dive deeper into its implementation, cracks in the facade begin to surface.</p><p>The hype surrounding Type Safe Navigation Compose is palpable, with promises of smoother navigation and improved compile-time safety. Yet, in practice, the reality often falls short of expectations. One glaring issue is the handling of server responses, particularly concerning default values for INT or BOOLEAN data types. This oversight not only complicates the integration of server data but also runs counter to established best practices.</p><p>Imagine a scenario where a server response lacks default values for certain data types. Suddenly, what should be a straightforward process becomes a tangled web of workarounds and compromises. As developers, we’re left grappling with the fallout, frantically patching up the cracks in our codebase.</p><p>But let’s not despair just yet. While Type Safe Navigation Compose may be bleeding, it’s not beyond salvation. By acknowledging these challenges and working collaboratively to address them, we can steer this ship back on course.</p><h4>Suggested Solutions:</h4><p>Instead of iterating through each parameter in the data class and converting it into an optional or default parameter string, why not convert the whole thing to a string using “GSON” and pass it as an optional parameter?</p><p>This way, during the receiving time, we could easily convert it back to the original object using the same “GSON” `fromJson` function. In this way, we could avoid unnecessary NavType definitions.</p><p>Suggested Route:<br>classname?args = {“name”:”boobalan”, “department”:”IT”}</p><h4>Conclusion</h4><p>In conclusion, Type Safe Navigation Compose holds immense promise for the Android ecosystem. However, its success hinges not only on the brilliance of its design but also on our collective efforts to refine and enhance its capabilities. Let’s roll up our sleeves, confront the challenges head-on, and chart a course towards a brighter, more navigable future for Android development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd09db244bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Kotlin Data Class Testing with Reflection]]></title>
            <link>https://medium.com/@boobalaninfo/streamlining-kotlin-data-class-testing-with-reflection-a584ffd8f39b?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/a584ffd8f39b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Tue, 07 May 2024 15:40:36 GMT</pubDate>
            <atom:updated>2024-05-07T15:40:36.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kZ7ugy7AS1EpCllL" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the landscape of modern software development, testing remains a cornerstone, ensuring that our code behaves as expected. Kotlin, with its concise syntax and functional features, has streamlined many aspects of writing code, particularly with the introduction of data classes. These classes automatically provide robust implementations of common methods like equals(), hashCode(), and toString(), based on the properties defined in the primary constructor. However, even with these conveniences, testing these methods can become repetitive and boilerplate-heavy, especially when aiming for high code coverage across many data classes. Let’s explore how Kotlin’s reflection capabilities can be leveraged to reduce the redundancy of writing JUnit tests for Kotlin data classes.</p><h3>The Challenge of Repetitive Testing Code</h3><p>When working with data classes in Kotlin, developers often find themselves writing repetitive test cases to validate the automatically generated methods (equals(), hashCode(), and toString()). Each data class, while having its automatic implementations, requires explicit testing to ensure these implementations are correct and to fulfill code coverage requirements. This can lead to numerous almost identical test functions across different test classes, which adds maintenance overhead and clutters the test suite.</p><h3>Kotlin Reflection to the Rescue</h3><p>Kotlin’s reflection API, provided by the kotlin-reflect library, offers a way to programmatically inspect classes and their properties at runtime. By using reflection, we can write generic test cases that automatically apply to all data classes without the need to manually write tests for each one.</p><h3>Setting Up kotlin-reflect</h3><p>First, ensure you have the Kotlin reflection library included in your project:</p><pre>// For Kotlin reflect<br>testImplementation (&quot;org.jetbrains.kotlin:kotlin-reflect:1.1.0&quot;)</pre><h3>Writing a Generic Test for Data Classes</h3><p>The idea is to create a generic test that can verify the behavior of equals() and hashCode() methods as expected.</p><pre>import io.github.classgraph.ClassGraph<br>import junit.framework.TestCase.assertEquals<br>import org.junit.Assert.assertNotEquals<br>import kotlin.reflect.KClass<br>import kotlin.reflect.full.createInstance<br>import kotlin.reflect.full.memberProperties<br>import kotlin.reflect.jvm.javaField<br><br><br>fun testDataClass(kClass: KClass&lt;*&gt;) {<br>    if (!kClass.isData) return  // Skip if it&#39;s not a data class<br><br>    val instance1 = kClass.createInstance()<br>    val instance2 = kClass.createInstance()<br>    val modifiedInstance = modifyInstance(kClass.createInstance(), kClass)<br><br>    // Test equality and hash code<br>    assertEquals(&quot;Instances should be equal&quot;,instance1, instance2)<br>    assertEquals(&quot;Hash codes should be the same for equal object&quot;,instance1.hashCode(), instance2.hashCode())<br>    assertNotEquals(&quot;Modified instance should not be equal to original&quot;, instance1, modifiedInstance)<br>}<br><br>private fun modifyInstance(instance: Any, kClass: KClass&lt;*&gt;): Any? {<br>    val props = kClass.memberProperties.first()<br>    val mutable = props.javaField!!.apply { isAccessible = true }<br>    mutable.set(<br>        instance, when (props.returnType.classifier) {<br>            String::class -&gt; &quot;Modified&quot;<br>            Int::class -&gt; 123<br>            Boolean::class -&gt; true<br>            Float::class-&gt;123.0f<br>            Double::class-&gt;123.0<br>            else -&gt; return try {<br>                (props.returnType.classifier as? KClass&lt;*&gt;)?.createInstance()<br>            } catch (ex:Exception) {<br>                null<br>            }<br>        }<br>    )<br>    return instance<br>}</pre><h3>How It Works</h3><ul><li>Filter Data Classes: The function skips any class that is not a data class.</li><li>Test Equality and Hash Codes: It checks that two instances of a class are equal and have the same hash code.</li><li>Modify an Instance: Changes one property to ensure the modified instance is not equal to the original.</li></ul><h3>Enhancing the Approach with ClassGraph</h3><p>To further automate the testing of Kotlin data classes using reflection, we integrate the ClassGraph library. ClassGraph excels at scanning the classpath to dynamically discover classes, including Kotlin’s data classes, eliminating the need to manually specify each data class in the test suite. This simplifies and further automates the process by allowing the test suite to automatically detect and test all data classes within specified packages.</p><h3>Step 1: Add Dependencies</h3><p>First, add the necessary dependencies for ClassGraph and JUnit to your build.gradle:</p><pre>  testImplementation (&quot;io.github.classgraph:classgraph:4.8.90&quot;)</pre><h3>Step 2: Implement the Automated Test</h3><p>Here’s how you can set up your JUnit tests to automatically find and test all data classes using ClassGraph and Kotlin reflection:</p><pre>fun getAllDataClasses(packageName: String): List&lt;KClass&lt;*&gt;&gt; {<br>    return ClassGraph()<br>        .enableAllInfo() // Enable all info<br>        .acceptPackages(packageName) // Set the package to scan<br>        .scan().use { scanResult -&gt;<br>            scanResult.allClasses.filterNot { it.name.contains(&quot;$&quot;) }<br>                .filterNot { it.name.endsWith(&quot;Kt&quot;) }<br>                .map { Class.forName(it.name).kotlin }<br>                .filter { it.isData }<br>        }<br>}</pre><p>This function uses ClassGraph to scan specified packages for all classes, filters for standard (non-inner) classes, loads them, and checks if they are data classes using Kotlin reflection.</p><h3>Step 3: Hook all together</h3><pre>class PiTestCoreModel {<br><br>    @Test<br>    fun `validate all code models`() {<br>        val lstDataClasses = getAllDataClasses(&quot;com.piappstudio.model&quot;)<br>        lstDataClasses.forEach {<br>            println(&quot;Testing: $it&quot;)<br>            testDataClass(it)<br>        }<br>    }<br>}</pre><h3>Advantages of This Approach</h3><ul><li>Automation: Automatically detects and tests all data classes, reducing manual setup and maintenance.</li><li>Scalability: Easily scalable as new data classes are added to the package, they are automatically included in the tests.</li><li>Flexibility: Can easily adjust the package name or scanning criteria to focus on different parts of the application.</li></ul><h3>Known Limitation</h3><ul><li>It works only on data classes at the moment.</li><li>All data class’s parameters should have default values to support default constructor invocation.</li></ul><p>This approach leverages the power of ClassGraph for discovery and Kotlin reflection for detailed testing, offering a robust and automated testing strategy for Kotlin data classes, significantly reducing boilerplate and enhancing maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a584ffd8f39b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate custom fonts in Kotlin/Compose Multiplatform]]></title>
            <link>https://medium.com/@boobalaninfo/integrate-custom-fonts-in-kotlin-compose-multiplatform-bc0f30c0b7e6?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0f30c0b7e6</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 18:31:38 GMT</pubDate>
            <atom:updated>2024-04-22T18:31:38.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>Youtube Video:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnXIdaaRlH3o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnXIdaaRlH3o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnXIdaaRlH3o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9252a4ac922549c98331c1c131e730c0/href">https://medium.com/media/9252a4ac922549c98331c1c131e730c0/href</a></iframe><h4>Prerequisite</h4><ul><li>Update your Compose version to 1.6.2.</li><li><a href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-images-resources.html#setup">Reference the following instruction</a>s for setting up your folder structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*ABCNpgn_GEkTA0IJ.png" /></figure><h4>Steps to Implement Custom Fonts:</h4><ol><li>Download Fonts: Begin by downloading your desired fonts from <a href="https://fonts.google.com/?preview.text=Bigg%20Boss%20Tamil">Google Fonts</a>. Look for fonts that suit your application’s aesthetic.</li><li>Place Fonts in the “font” Folder: Once downloaded, place these font files under the “font” folder within your project’s resources.</li><li>Create Font.kt Under Theme Folder: Navigate to your theme folder and create a file named Font.kt. Add the following code:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*xLgXzw_xKVMlwZmc-xo-2A.png" /></figure><pre>package ui.theme<br><br>import androidx.compose.material3.Typography<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.text.font.FontFamily<br>import androidx.compose.ui.text.font.FontWeight<br>import bigboss.shared.generated.resources.Res<br>import bigboss.shared.generated.resources.teko_bold<br>import bigboss.shared.generated.resources.teko_light<br>import bigboss.shared.generated.resources.teko_medium<br>import bigboss.shared.generated.resources.teko_regular<br>import bigboss.shared.generated.resources.teko_semibold<br>import org.jetbrains.compose.resources.ExperimentalResourceApi<br>import org.jetbrains.compose.resources.Font<br><br>@OptIn(ExperimentalResourceApi::class)<br>@Composable<br>fun TekoFontFamily() = FontFamily(<br>    Font(Res.font.teko_light, weight = FontWeight.Light),<br>    Font(Res.font.teko_regular, weight = FontWeight.Normal),<br>    Font(Res.font.teko_medium, weight = FontWeight.Medium),<br>    Font(Res.font.teko_semibold, weight = FontWeight.SemiBold),<br>    Font(Res.font.teko_bold, weight = FontWeight.Bold)<br>)<br><br>@Composable<br>fun TekoTypography() = Typography().run {<br><br>    val fontFamily = TekoFontFamily()<br>    copy(<br>        displayLarge = displayLarge.copy(fontFamily = fontFamily),<br>        displayMedium = displayMedium.copy(fontFamily = fontFamily),<br>        displaySmall = displaySmall.copy(fontFamily = fontFamily),<br>        headlineLarge = headlineLarge.copy(fontFamily = fontFamily),<br>        headlineMedium = headlineMedium.copy(fontFamily = fontFamily),<br>        headlineSmall = headlineSmall.copy(fontFamily = fontFamily),<br>        titleLarge = titleLarge.copy(fontFamily = fontFamily),<br>        titleMedium = titleMedium.copy(fontFamily = fontFamily),<br>        titleSmall = titleSmall.copy(fontFamily = fontFamily),<br>        bodyLarge = bodyLarge.copy(fontFamily =  fontFamily),<br>        bodyMedium = bodyMedium.copy(fontFamily = fontFamily),<br>        bodySmall = bodySmall.copy(fontFamily = fontFamily),<br>        labelLarge = labelLarge.copy(fontFamily = fontFamily),<br>        labelMedium = labelMedium.copy(fontFamily = fontFamily),<br>        labelSmall = labelSmall.copy(fontFamily = fontFamily)<br>    )<br>}</pre><h4>Update MaterialTheme Initialization in Theme.kt:</h4><p>Integrate the custom typography into your MaterialTheme by updating the initialization function in Theme.kt:</p><pre> MaterialTheme(<br>      typography = TekoTypography(),<br>    colorScheme = colors,<br>    content = content<br>  )</pre><p>That’s it! Following these steps, you will successfully integrate custom fonts into your Kotlin/Compose Multiplatform application, enhancing the visual appeal and user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0f30c0b7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Article 2: Bringing Compose Multiplatform to Life: Seamlessly Incorporating ktor, koin, and voyagar…]]></title>
            <link>https://medium.com/@boobalaninfo/article-2-bringing-compose-multiplatform-to-life-seamlessly-incorporating-ktor-koin-and-voyagar-76e4db6c15fe?source=rss-7a32b6599f65------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e4db6c15fe</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Boobalan Munusamy]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 11:18:17 GMT</pubDate>
            <atom:updated>2023-10-09T11:18:17.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Article 2: Bringing Compose Multiplatform to Life: Seamlessly Incorporating ktor, koin, and voyagar Integration</h3><p>This article is a follow-up to my previous piece on the BiggBoss voting app. I recommend reading the previous document and referring to the associated YouTube content for context</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0s4tH0U83gU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0s4tH0U83gU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0s4tH0U83gU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4e6e749b749b34de4ffeffc32b22335/href">https://medium.com/media/b4e6e749b749b34de4ffeffc32b22335/href</a></iframe><p>Previous article: <a href="https://medium.com/@boobalaninfo/article-1-compose-multiplatform-moko-resource-integration-dbccbf19aab7">https://medium.com/@boobalaninfo/article-1-compose-multiplatform-moko-resource-integration-dbccbf19aab7</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*HFDNl3lRlRY-Ft1LTWl4ow.png" /><figcaption>Android Home Screen</figcaption></figure><h3>Quick Introduction:</h3><p>In the context of Compose Multiplatform development, it’s essential to have libraries that provide support across all platforms. Traditional options like Hilt for Android or Retrofit may not offer this level of cross-platform compatibility at the moment. Therefore, I’ve chosen some well-known libraries to fulfill this role temporarily</p><blockquote><a href="https://github.com/ktorio/ktor">Ktor</a> — http client</blockquote><blockquote><a href="https://github.com/InsertKoinIO/koin">Koin</a> — DI framework (For dependence injection)</blockquote><blockquote><a href="https://github.com/adrielcafe/voyager">Voyager</a> Compose Multiplatform Navigation</blockquote><h3>Configurations</h3><p>libs.versions.toml</p><pre>[versions]<br>ktor-version = &quot;2.3.4&quot;<br>koin-version = &quot;1.1.0&quot;<br>voyagerVersion = &quot;1.0.0-rc05&quot;<br>[libraries]<br><br>ktor-client-core = {group = &quot;io.ktor&quot;, name = &quot;ktor-client-core&quot;, version.ref= &quot;ktor-version&quot;}<br>ktor-android = {group = &quot;io.ktor&quot;, name = &quot;ktor-client-android&quot;, version.ref = &quot;ktor-version&quot; }<br>ktor-ios = {group = &quot;io.ktor&quot;, name = &quot;ktor-client-darwin&quot;, version.ref = &quot;ktor-version&quot;}<br>ktor-desktop = {group = &quot;io.ktor&quot;, name = &quot;ktor-client-cio&quot;, version.ref = &quot;ktor-version&quot;}<br><br><br>koin-compose = {group=&quot;io.insert-koin&quot;, name = &quot;koin-compose&quot;, version.ref = &quot;koin-version&quot;}<br><br>voyager-navigator =  {group = &quot;cafe.adriel.voyager&quot;, name = &quot;voyager-navigator&quot;, version.ref= &quot;voyagerVersion&quot;}<br>voyager-bottom-sheet =  {group = &quot;cafe.adriel.voyager&quot;, name = &quot;voyager-bottom-sheet-navigator&quot;, version.ref= &quot;voyagerVersion&quot;}<br>voyager-tab-navigator =  {group = &quot;cafe.adriel.voyager&quot;, name = &quot;voyager-tab-navigator&quot;, version.ref= &quot;voyagerVersion&quot;}<br>voyager-transitions =  {group = &quot;cafe.adriel.voyager&quot;, name = &quot;voyager-transitions&quot;, version.ref= &quot;voyagerVersion&quot;}<br># For koin integration https://voyager.adriel.cafe/screenmodel/koin-integration<br>voyager-koin =  {module = &quot;cafe.adriel.voyager:voyager-koin&quot;, version.ref= &quot;voyagerVersion&quot;}<br><br><br>[bundles]<br>voyager = [&quot;voyager-navigator&quot;, &quot;voyager-bottom-sheet&quot;, &quot;voyager-tab-navigator&quot;, &quot;voyager-transitions&quot;, &quot;voyager-koin&quot;]<br>ktor = [&quot;ktor-client-core&quot;, &quot;ktor-client-content-negotiation&quot;, &quot;ktor-serialization-kotlinx-json&quot;]</pre><p>Project configurations</p><p>At shared project: <a href="https://github.com/piappstudio/BiggBoss/compare/feature/listshow?expand=1#diff-cf9ae3b1eb7273a914f22b1e6d22d8447f88df0e7245a5b856fb751e507b979b">shared/build.gradle.kts</a></p><p><strong><em>Please note, I’m showing only the delta changes here.</em></strong></p><pre><br>val commonMain by getting {<br>            dependencies {<br>                <br>                // For DI<br>                implementation(libs.koin.compose)<br><br>                // For networking<br>                implementation(libs.bundles.ktor)<br><br>                // For navigation<br>                implementation( libs.bundles.voyager)<br><br>            }<br>}<br>  val iosMain by creating {<br>            dependencies {<br>                implementation(libs.ktor.ios)<br>            }<br>        }<br><br>val  androidMain by getting {<br>            dependencies {<br>                implementation(libs.ktor.android)<br>            }<br>        }<br> val desktopMain by getting {<br>    dependencies {<br>           implementation(libs.ktor.client.core)<br>           implementation(libs.ktor.desktop)<br>        }<br><br>}</pre><p>Let’s dive right into creating a repository for making network calls. We’ll start by establishing a ‘network’ package within the shared project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*KELsmGfXg40QVVQr0pJuQQ.png" /></figure><pre>package network<br><br>import di.PiNetwork<br>import di.isNetworkAvailable<br>import io.ktor.client.HttpClient<br>import io.ktor.client.call.body<br>import io.ktor.client.request.get<br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.flow.flow<br>import model.ShowDetail<br>import model.ShowList<br><br>class PiRepository (private val httpClient:HttpClient) {<br><br>    fun fetchShows():Flow&lt;Resource&lt;ShowList?&gt;&gt; {<br>        return makeSafeApiCall {<br>            val response = httpClient.get(PiNetwork.URL.plus(PiNetwork.EndPoint.SHOWS)).body&lt;ShowList&gt;()<br>            Resource.success(response)<br>        }<br>    }<br>    fun fetchDetail(showId:String):Flow&lt;Resource&lt;ShowDetail?&gt;&gt; {<br>        return makeSafeApiCall {<br>            val response = httpClient.get(showId).body&lt;ShowDetail&gt;()<br>            Resource.success(response)<br>        }<br>    }<br>    private fun &lt;T&gt; makeSafeApiCall(api:suspend ()-&gt; Resource&lt;T?&gt;) = flow {<br>        try {<br>            emit(Resource.loading())<br>            if (isNetworkAvailable()) {<br>               val response = api.invoke()<br>                emit(Resource.success(response.data))<br>            } else {<br>                emit(Resource.error(error = PIError(code = ErrorCode.NETWORK_NOT_AVAILABLE)))<br>            }<br><br>        }catch (ex:Exception) {<br>            emit(Resource.error(error = PIError(code = ErrorCode.NETWORK_CONNECTION_FAILED)))<br>        }<br><br>    }<br>    <br>}</pre><pre><br>// Supporting class<br>data class Resource&lt;out T&gt;(val status: Status, val data: T?, val error: PIError?){<br><br>    companion object {<br>        //Handles success<br>        fun &lt;T&gt; success(data: T): Resource&lt;T&gt; = Resource(<br>            status = Status.SUCCESS, data = data, error = null)<br>        //Handles Loading<br>        fun &lt;T&gt; loading(data: T?=null): Resource&lt;T&gt; = Resource(<br>            status = Status.LOADING, data = data, error = null)<br>        //Handles Error<br>        fun &lt;T&gt; error(data: T?=null, error: PIError?=null): Resource&lt;T&gt; = Resource(<br>            status = Status.ERROR, data = data, error=error)<br>        fun&lt;T&gt; idle(data:T?) = Resource (status = Status.NONE, data = data, error = null)<br><br>    }<br>    enum class Status {<br>        NONE,<br>        SUCCESS,<br>        ERROR,<br>        LOADING<br>    }<br>}<br><br></pre><p>Now, you might be wondering if you need to manually create the `httpClient` object. Well, the answer is NOPE.<br>Let’s delegate that task to Koin. Create a `NetworkModule.kt` file within the ‘DI’ folder in the shared project, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*parvh_OWUVZRCOfxv-RLKw.png" /><figcaption>Folder stcture</figcaption></figure><pre>object PiNetwork {<br>    const val URL =  &quot;https://raw.githubusercontent.com/piappstudio/resources/main/biggboss/&quot;<br>    object EndPoint {<br>        const val SHOWS = &quot;json/shows.json&quot;<br>        const val DETAIL = &quot;json/shows/&quot;<br>    }<br>}<br><br>val httpClientModule = module {<br>    single {<br>        HttpClient {<br>            install(ContentNegotiation) {<br>                json(json = Json { ignoreUnknownKeys = true }, contentType = ContentType.Any)<br>            }<br>        }<br>    }<br>}<br>val repositoryModule = module {<br>    single&lt;PiRepository&gt; { PiRepository(get()) }<br>}<br>// This is yet to be implemented, just retur true at the moment<br>expect fun isNetworkAvailable():Boolean</pre><p>It’s a time to create home page to access the shows information from github.</p><p>Creating <strong><em>HomeScreen &amp; HomeScreenViewModel</em></strong> for the same in shared-&gt;src-&gt;commonMain-&gt;Kotlin-&gt;ui folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*kLvTFS80OE7-tJZ-OMuyNg.png" /></figure><p>HomeScreenViewModel</p><pre>package ui.home<br>import cafe.adriel.voyager.core.model.ScreenModel<br>import cafe.adriel.voyager.core.model.coroutineScope<br>import io.github.aakira.napier.Napier<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.IO<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.SharingStarted<br>import kotlinx.coroutines.flow.StateFlow<br>import kotlinx.coroutines.flow.map<br>import kotlinx.coroutines.flow.stateIn<br>import kotlinx.coroutines.flow.update<br>import kotlinx.coroutines.launch<br>import model.ShowList<br>import network.PIError<br>import network.PiRepository<br>import network.Resource<br><br>/**<br> * Defined all possible states here<br> * */<br>sealed class HomeScreenState {<br>    data object Loading: HomeScreenState()<br>    data class Error(val piError: PIError):HomeScreenState()<br>    data class Success(val showList: ShowList?):HomeScreenState()<br>}<br><br>/**<br> * Additional data states to hold all possible data<br> * */<br><br>private data class HomeState(<br>    val isLoading:Boolean = false,<br>    val piError: PIError?=null,<br>    val showList: ShowList?=null<br>) {<br>    fun toUiState(): HomeScreenState {<br>        if (isLoading) {<br>           return HomeScreenState.Loading<br>        } else if(piError!=null) {<br>            return HomeScreenState.Error(piError)<br>        } else {<br>            return HomeScreenState.Success(showList)<br>        }<br>    }<br>}<br>class HomeScreenModel(piRepository: PiRepository): ScreenModel {<br><br>    private val _homeState = MutableStateFlow(HomeState())<br><br>    val uiState:StateFlow&lt;HomeScreenState&gt; = piRepository.fetchShows().map {response -&gt;<br>        Napier.d(&quot;Result: $response&quot;)<br>         when (response.status) {<br>            Resource.Status.ERROR -&gt; {<br>                _homeState.update { it.copy(isLoading = false, piError = response.error) }<br>            }<br>            Resource.Status.LOADING -&gt; {<br>                _homeState.update { it.copy(isLoading = true) }<br>            } else -&gt; {<br>                Napier.d(message = response.data?.toString()?:&quot;&quot;)<br>                _homeState.update { it.copy(isLoading = false, piError = null, showList = response.data) }<br>            }<br>        }<br>        _homeState.value.toUiState()<br><br>    }.stateIn(coroutineScope, SharingStarted.WhileSubscribed(500L), HomeScreenState.Loading)<br><br>}</pre><p>Again, we need to delegate the viewModel creation job to Koin. Create ViewModelModule.kt in DI folder. Here, I’m using below to create factory</p><pre>module {<br>factory {<br>        HomeScreenModel(get())<br>    }<br>}</pre><pre>package di<br><br>import androidx.compose.runtime.Composable<br>import cafe.adriel.voyager.core.model.ScreenModel<br>import cafe.adriel.voyager.core.model.rememberScreenModel<br>import cafe.adriel.voyager.core.screen.Screen<br>import org.koin.compose.getKoin<br>import org.koin.core.parameter.ParametersDefinition<br>import org.koin.core.qualifier.Qualifier<br>import org.koin.dsl.module<br>import ui.detail.ShowDetailModel<br>import ui.home.HomeScreenModel<br><br>@Composable<br>public inline fun &lt;reified T : ScreenModel&gt; Screen.getScreenModel(<br>    qualifier: Qualifier? = null,<br>    noinline parameters: ParametersDefinition? = null<br>): T {<br>    val koin = getKoin()<br>    return rememberScreenModel(tag = qualifier?.value) { koin.get(qualifier, parameters) }<br>}<br><br>val viewModel = module {<br><br>    factory {<br>        HomeScreenModel(get())<br>    }<br>    factory {<br>        ShowDetailModel(get())<br>    }<br><br>}</pre><p>Let’s design HomeScreen now.</p><pre>class HomeScreen : Screen {<br><br>    @OptIn(ExperimentalMaterial3Api::class)<br>    @Composable<br>    override fun Content() {<br>        val homeScreenModel = getScreenModel&lt;HomeScreenModel&gt;()<br>        val state by homeScreenModel.uiState.collectAsState()<br>        val currentNav = LocalNavigator.currentOrThrow<br>        Scaffold(topBar = {<br>            TopAppBar(title = {<br>                Text(stringResource(MR.strings.title_home))<br>            })<br><br>        }) { // TODO Design <br>             }<br>      }<br>}</pre><p>We have 2 Ktor modules at the moment, let’s group it together and initialize it in App</p><p><strong>AppModule.kt</strong></p><pre>fun appModule() = listOf(httpClientModule, repositoryModule, viewModel)</pre><p>Initialize it in <strong>App.kt</strong></p><pre><br>@OptIn(ExperimentalResourceApi::class)<br>@Composable<br>fun App() {<br><br>    KoinApplication(application = {<br>        modules(appModule())<br>    }) {<br>        BiggBossAppTheme {<br>            Navigator(screen = HomeScreen())<br>        }<br>    }<br>}</pre><p>Repository: <a href="https://github.com/piappstudio/BiggBoss">https://github.com/piappstudio/BiggBoss</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e4db6c15fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>