<?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 Fergus A Hewson on Medium]]></title>
        <description><![CDATA[Stories by Fergus A Hewson on Medium]]></description>
        <link>https://medium.com/@fergus.a.hewson?source=rss-fe3762fb29c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TCneCEglINdmyOt-</url>
            <title>Stories by Fergus A Hewson on Medium</title>
            <link>https://medium.com/@fergus.a.hewson?source=rss-fe3762fb29c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:43:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fergus.a.hewson/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[Understanding and Resolving Poor Error Messages for Unimplemented expect Declarations in Kotlin…]]></title>
            <link>https://medium.com/@fergus.a.hewson/understanding-and-resolving-poor-error-messages-for-unimplemented-expect-declarations-in-kotlin-662f92751844?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/662f92751844</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetbrains]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 22:21:35 GMT</pubDate>
            <atom:updated>2024-09-16T22:21:35.587Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding and Resolving Poor Error Messages for Unimplemented </strong>expect<strong> Declarations in Kotlin Multiplatform</strong></h3><p>Kotlin Multiplatform (KMP) is an incredibly powerful tool for sharing code across different platforms. However, as with any complex system, there are sometimes error messages that don’t quite point developers in the right direction. One specific scenario that developers might encounter is related to the use of expect/actual declarations. When expect functions or properties are not implemented in the consuming source sets, the compiler may throw cryptic and unhelpful error messages, leaving developers scratching their heads.</p><p>Let’s dive into this issue, see an example, and explore how you can resolve it.</p><h4><strong>Problem Overview</strong></h4><p>Kotlin’s expect/actual mechanism allows you to define platform-independent declarations (expect) and provide platform-specific implementations (actual). The compiler ensures that every expect declaration in a shared (common) module is matched by an actual implementation in platform-specific modules.</p><p>However, if you forget to implement an expect function or property in one of the target source sets, the error message you receive is vague, confusing, and often has little to do with the actual issue. Here’s an example of such a cryptic error:</p><pre>org.jetbrains.kotlin.backend.common.CompilationException: Back-end: Please report this problem https://kotl.in/issue<br>SomeKt:-1:-1<br>Details: Internal error in file lowering: java.lang.IllegalStateException: should not be called<br> at org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt.shouldNotBeCalled(addToStdlib.kt:323)<br> at org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt.shouldNotBeCalled$default(addToStdlib.kt:322)<br> at org.jetbrains.kotlin.ir.symbols.impl.IrFakeOverrideSymbolBase.getOwner(IrFakeOverrideSymbol.kt:41)<br> at org.jetbrains.kotlin.ir.symbols.impl.IrFakeOverrideSymbolBase.getOwner(IrFakeOverrideSymbol.kt:20)</pre><p>This error might appear in a random file in your common source set (like SomeKt), leaving you with no clear idea where the root cause lies. There is no direct mention of the expect function or where its implementation might be missing. As a result, debugging becomes a frustrating guessing game.</p><h4><strong>A Typical Scenario</strong></h4><p>Here’s an example of code that triggers the issue:</p><pre>interface A<br>expect fun getA(): A</pre><p>n this case, getA() is declared as an expect function in the common module, meaning we expect platform-specific implementations of this function. However, if you forget to provide the actual implementations in the consuming platform source sets (e.g., for JVM, iOS, etc.), you might end up with the aforementioned cryptic error message.</p><p><strong>Why Does This Happen?</strong></p><p>The issue stems from how Kotlin’s backend processes unimplemented expect declarations. When the backend tries to resolve the missing actual implementation, it encounters a situation it doesn’t know how to handle and throws an internal exception like java.lang.IllegalStateException: should not be called. This exception, in turn, generates an error message that lacks sufficient context or helpful information for the developer.</p><p>The mention of SomeKt:-1:-1 doesn’t indicate the file or the line number that triggered the issue, which adds to the confusion. The error is effectively “random,” providing no clues as to the missing implementation.</p><h4><strong>How to Identify the Root Cause</strong></h4><p>When faced with this error, it’s easy to get stuck trying to debug the wrong areas of the code. Here are some steps to help you identify the missing actual implementation:</p><p>1. <strong>Review </strong>expect<strong> Declarations</strong>: Start by reviewing all the expect functions and properties in your common source sets. Ensure that each one has a corresponding actual implementation in every platform source set.</p><p>2. <strong>Platform Source Sets</strong>: Check your platform-specific source sets (e.g., JVM, iOS, JS) to confirm that the actual keyword is used for each expect declaration.</p><p>3. <strong>Incremental Compilation Check</strong>: Sometimes, incremental builds might obscure the real cause of the issue. Try doing a <strong>clean build</strong> (i.e., ./gradlew clean build) to ensure you’re working with a fresh state.</p><p>4. <strong>Look for Missing </strong>actual<strong> Implementations</strong>: Manually check the platform-specific modules for any missing actual implementations of expect declarations.</p><h4><strong>Hope for Better Error Messages</strong></h4><p>While the current error messages for missing actual implementations are not particularly helpful, there’s hope that Kotlin’s development team will improve these messages in future releases. For now, developers need to be aware of this potential issue and know how to troubleshoot it.</p><h4><strong>Conclusion</strong></h4><p>If you encounter a random internal error like java.lang.IllegalStateException: should not be called or a compilation error in a seemingly unrelated file, remember that the real issue might be missing actual implementations for your expect declarations.</p><p>While the error message might not point you in the right direction, reviewing your expect functions and their platform-specific implementations should help resolve the issue.</p><p>I hope this explanation sheds some light on a tricky situation and saves someone from hours of frustration. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=662f92751844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Android Room and DataStore Dependencies from CommonMain for Kotlin Multiplatform to…]]></title>
            <link>https://medium.com/@fergus.a.hewson/extracting-android-room-and-datastore-dependencies-from-commonmain-for-kotlin-multiplatform-to-f1e18e2a7458?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e18e2a7458</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin-mu]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-room]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 03:51:25 GMT</pubDate>
            <atom:updated>2024-09-14T03:51:25.983Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Extracting Android Room and DataStore Dependencies from CommonMain for Kotlin Multiplatform to support WASM</strong></h3><p>Kotlin Multiplatform (KMP) allows you to share code across various platforms, including Android, iOS, and JavaScript. However, when targeting new platforms like WebAssembly (WASM), Android-specific dependencies such as Room and DataStore are not supported since they are designed only for mobile environments like Android and iOS.</p><p>In this blog, we will discuss how to refactor a Kotlin Multiplatform project by extracting Android Room and DataStore dependencies from the common main source set, allowing the code to compile for the WASM target without issues. We’ll also demonstrate how to organize the project structure to maintain shared code across platforms.</p><h4><strong>Problem: Android Dependencies Not Available on WASM Target</strong></h4><p>When building Kotlin Multiplatform projects, you often define shared logic in the commonMain source set. However, dependencies like Android Room and DataStore are only available on mobile platforms (i.e., Android and iOS). If you try to compile your project for WASM (or any non-mobile platform), the build will fail because these dependencies are not present for the WASM target.</p><p>To resolve this issue, you need to extract platform-specific dependencies out of the commonMain source set, isolating them for the mobile platforms while keeping the shared logic intact.</p><h4><strong>Solution: Introducing a mobileMain Source Set</strong></h4><p>To isolate mobile-specific code, we can create a mobileMain source set that contains Android and iOS-specific dependencies such as Room and DataStore. This will allow you to keep common logic in commonMain while only including the mobile dependencies in a mobile-specific source set.</p><p>Here’s how you can set up the mobileMain source set inside your shared module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f423acde91acf0f0f2f28bb8a3e3ef5/href">https://medium.com/media/9f423acde91acf0f0f2f28bb8a3e3ef5/href</a></iframe><p>The mobileMain source set depends on commonMain, meaning it can still access the shared code, but the Room and DataStore libraries will be confined to mobile platforms (Android and iOS).</p><p>Once mobileMain is set up, both androidMain and iosMain source sets should depend on it. With this structure, mobileMain contains all the mobile-specific logic and is shared between androidMain and iosMain.</p><h4><strong>Refactoring Room and DataStore Implementations</strong></h4><p>Next, we’ll move the Room and DataStore implementations from commonMain to mobileMain. To ensure the shared module still compiles across all platforms, we’ll use expect/actual declarations or dependency injection (DI) with Koin to provide platform-specific implementations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2deb00edb96d5ef9bce92b090b5c05/href">https://medium.com/media/8f2deb00edb96d5ef9bce92b090b5c05/href</a></iframe><h4><strong>Using Koin for Dependency Injection</strong></h4><p>Alternatively, you can use Koin to inject platform-specific dependencies. Here’s how to set up a shared Koin module and a platform-specific module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28fd6d0141cc5d5dbd0d7e11faaa153/href">https://medium.com/media/f28fd6d0141cc5d5dbd0d7e11faaa153/href</a></iframe><h4><strong>Compiling for WASM Without Mobile Dependencies</strong></h4><p>With the Android Room and DataStore dependencies isolated in mobileMain, the WASM target can now compile without issues. Since the WASM target does not include the mobileMain source set, it avoids pulling in the mobile-specific libraries, allowing you to build and run your code on WebAssembly.</p><h4><strong>Future Work: Implementing Repositories for WASM</strong></h4><p>While this refactor solves the compilation issues for WASM, you still need to provide platform-specific implementations of repositories for the WASM target. This might involve writing JavaScript or WebAssembly-specific data storage mechanisms to replace Room and DataStore on the web.</p><p>But that’s a story for another day! For now, you have successfully extracted the Android Room and DataStore dependencies from commonMain and can confidently target WASM without breaking your Kotlin Multiplatform project.</p><p>In summary, by refactoring your source sets to create a mobileMain, you can separate mobile-specific dependencies and implementations, ensuring your project remains compatible with all platforms, including WASM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e18e2a7458" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid White Background Glitches in iOS Dark Mode: The Importance of Using Surface as Your Root View…]]></title>
            <link>https://medium.com/@fergus.a.hewson/avoid-white-background-glitches-in-ios-dark-mode-the-importance-of-using-surface-as-your-root-view-18eab4541984?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/18eab4541984</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 04:20:12 GMT</pubDate>
            <atom:updated>2024-08-26T04:20:12.685Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Avoid White Background Glitches in iOS Dark Mode: The Importance of Using Surface as Your Root View in Jetpack Compose</strong></h3><p>As more developers embrace Jetpack Compose Multiplatform, creating visually consistent apps across Android and iOS has become easier than ever. However, there’s a small but critical detail that can be easily overlooked, especially when deploying your Compose-based app on iOS: the appearance of an unexpected white background when the app is viewed in Dark Mode.</p><p>In this article, I’ll show you how to avoid this issue with a simple, yet often forgotten, practice: always use a Surface as the root view of your app. Let’s dive in!</p><h4><strong>The Problem: White Background in iOS Dark Mode</strong></h4><p>When developing with Jetpack Compose, the natural instinct is to build your UI components without worrying too much about underlying platform-specific quirks. However, one common issue arises on iOS when your app is displayed in Dark Mode. If the root view of your Compose tree isn’t wrapped in a Surface, you might end up with a glaring white background, which can be jarring and inconsistent with the rest of your app’s dark theme.</p><h4><strong>The Solution: Wrapping Your Root View in a Surface</strong></h4><p>To prevent this from happening, it’s essential to make Surface the root view of your Compose tree. Surface is a composable that provides a material-themed background, automatically adjusting to the theme (light or dark) your app is currently using.</p><p>Here’s a quick example to illustrate this:</p><pre>PreComposeApp {<br>    AppTheme {<br>        val navigator = rememberNavigator()<br>        // Ensure the root view is a Surface<br>        Surface(modifier = Modifier.fillMaxSize()) {<br>            NavHost(<br>                navigator = navigator,<br>                initialRoute = Screen.MainScreen.route<br>            ) {<br>                // Your composable screens here<br>            }<br>        }<br>    }<br>}</pre><h4><strong>Why Use Surface?</strong></h4><p>Surface ensures that your app respects the current theme, whether light or dark, by applying the appropriate background color. This prevents any unwanted white backgrounds from appearing when your app is viewed in Dark Mode on iOS.</p><h4><strong>Key Benefits:</strong></h4><p>• <strong>Theme Consistency:</strong> Surface aligns with your theme’s colors, maintaining a consistent look across different modes.</p><p>• <strong>Avoid White Backgrounds:</strong> Prevents the jarring white background glitch in iOS Dark Mode.</p><p>• <strong>Material Design Principles:</strong> Surface is part of the Material Design components in Compose, ensuring your app adheres to modern UI/UX standards.</p><h4><strong>Conclusion</strong></h4><p>As you continue to build cross-platform apps with Jetpack Compose, always remember to use Surface as the root of your composable hierarchy. This small step ensures that your app’s appearance remains consistent and polished, especially when running on iOS in Dark Mode.</p><p>Incorporating Surface is a quick fix, but it has a big impact on user experience. Don’t let a small oversight lead to a glaring white background — wrap it up with Surface!</p><p>By keeping this simple tip in mind, you’ll be well on your way to delivering a smooth, visually consistent experience across both Android and iOS. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18eab4541984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Firebase Analytics on iOS with Kotlin Multiplatform]]></title>
            <link>https://medium.com/@fergus.a.hewson/how-to-integrate-firebase-analytics-on-ios-with-kotlin-multiplatform-2aa147abca15?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa147abca15</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 19:38:25 GMT</pubDate>
            <atom:updated>2024-08-22T19:38:25.866Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin Multiplatform (KMP) is a powerful tool for sharing code between Android and iOS, but integrating platform-specific libraries like Firebase Analytics can be tricky — especially on iOS. In this article, I’ll walk you through a simple yet effective trick to get Firebase Analytics working on iOS using KMP.</p><h4><strong>Step 1: Define the Analytics Interface in Common Code</strong></h4><p>First, you need to set up an expectation for your analytics implementation in the commonMain source set. This allows you to define a common interface that will be implemented differently on each platform.</p><pre>expect fun getXAnalytics(): IXAnalytics<br>interface IXAnalytics {<br> fun logEvent(eventName: String, params: Map&lt;String, Any&gt;?)<br>}</pre><p>The IXAnalytics interface defines a single method, logEvent, which will be responsible for logging events with optional parameters.</p><h4><strong>Step 2: Implement Analytics on Android</strong></h4><p>On Android, integrating Firebase Analytics is straightforward. You create a logger class that implements IXAnalytics and directly interacts with Firebase.</p><pre>class XAnalytics : IXAnalytics {<br>    private val context: Context = KoinPlatform.getKoin().get()<br>    private val firebaseAnalytics = FirebaseAnalytics.getInstance(context)<br><br>    override fun logEvent(eventName: String, params: Map&lt;String, Any&gt;?) {<br>        val bundle: Bundle? = params?.run {<br>            val bundle = Bundle()<br>            this.forEach { (t, u) -&gt;<br>                when (u) {<br>                    is String -&gt; bundle.putString(t, u)<br>                    is Int -&gt; bundle.putInt(t, u)<br>                    is Long -&gt; bundle.putLong(t, u)<br>                    is Float -&gt; bundle.putFloat(t, u)<br>                    is Double -&gt; bundle.putDouble(t, u)<br>                    else -&gt; bundle.putString(t, u.toString())<br>                }<br>            }<br>            bundle<br>        }<br>        firebaseAnalytics.logEvent(eventName, bundle)<br>    }<br>}</pre><p>This code creates an instance of FirebaseAnalytics and uses it to log events, converting the parameter map into a Bundle that Firebase can understand.</p><h4><strong>Step 3: Implement Analytics on iOS</strong></h4><p>On iOS, things get a bit more complex because you have to call back into Swift from Kotlin. Due to platform limitations, you can only pass primitive data types between Swift and Kotlin. To work around this, you’ll serialize your parameters into a string and then parse it in Swift.</p><p><strong>Swift Setup</strong></p><p>First, in your AppDelegate, configure Firebase and set up a callback for Kotlin to invoke when logging events.</p><pre>class AppDelegate: NSObject, UIApplicationDelegate {<br>    func application(_ application: UIApplication,<br>                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>        FirebaseApp.configure()<br>        XAnalytics_iosKt.firebaseCallback(callback: FirebaseLoggingCallback())<br>        return true<br>    }<br>}<br><br>class FirebaseLoggingCallback: FirebaseIosCallback {<br>    <br>    func logEvent(eventId: String, params: String) {<br>        let dict = splitStringToDictionary(params, &quot;,&quot;, &quot;:&quot;)<br>        Analytics.logEvent(eventId, parameters: dict)<br>    }<br>     <br>    func splitStringToDictionary(_ input: String, _ pairDelimiter: Character, _ keyValueDelimiter: Character) -&gt; [String: String] {<br>        var result = [String: String]()<br>        <br>        let pairs = input.split(separator: pairDelimiter)<br>        <br>        for pair in pairs {<br>            let keyValueArray = pair.split(separator: keyValueDelimiter, maxSplits: 1).map { String($0) }<br>            if keyValueArray.count == 2 {<br>                let key = keyValueArray[0].trimmingCharacters(in: .whitespacesAndNewlines)<br>                let value = keyValueArray[1].trimmingCharacters(in: .whitespacesAndNewlines)<br>                result[key] = value<br>            }<br>        }<br>        <br>        return result<br>    }<br>}</pre><p>Here, FirebaseLoggingCallback implements FirebaseIosCallback and is responsible for converting the stringified parameters back into a dictionary that Firebase can use.</p><p><strong>Kotlin Implementation</strong></p><p>In Kotlin, implement the IXAnalytics interface for iOS, invoking the callback method to pass event data to Swift.</p><pre>class XAnalytics : IXAnalytics {<br>    override fun logEvent(<br>        eventName: String,<br>        params: Map&lt;String, Any&gt;?<br>    ) {<br>        firebaseIosCallback?.logEvent(eventName, params.toString())<br>    }<br><br>    private fun Map&lt;String, Any&gt;?.toString(): String {<br>        if (this == null) return &quot;&quot;<br><br>        val sb = StringBuilder()<br>        this.forEach {<br>            sb.append(&quot;${it.key}:${it.value},&quot;)<br>        }<br>        return sb.toString()<br>    }<br>}<br><br>actual fun getXAnalytics(): IXAnalytics = XAnalytics()<br><br>interface FirebaseIosCallback {<br>    fun logEvent(eventId: String, params: String)<br>}<br><br>private var firebaseIosCallback: FirebaseIosCallback? = null<br><br>@Suppress(&quot;unused&quot;)<br>fun firebaseCallback(callback: FirebaseIosCallback) {<br>    firebaseIosCallback = callback<br>}</pre><p>The logEvent method serializes the event parameters into a string and sends them to Swift via the firebaseIosCallback.</p><h4><strong>Conclusion</strong></h4><p>Integrating Firebase Analytics on iOS with Kotlin Multiplatform may seem challenging at first, but with the right approach, you can bridge the gap between Kotlin and Swift. By using primitive data types and callbacks, you can successfully log analytics events across both Android and iOS, maintaining a shared codebase.</p><p>This trick helps keep your KMP project clean and consistent, allowing you to leverage Firebase Analytics without compromising on platform-specific requirements. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa147abca15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP Room Alpha07 Config]]></title>
            <link>https://medium.com/@fergus.a.hewson/kmp-room-alpha07-config-53da35074ddb?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/53da35074ddb</guid>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android-room]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 01:23:08 GMT</pubDate>
            <atom:updated>2024-08-22T06:43:16.260Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuring Room Alpha-07 in Your Project</h3><p>Room Alpha-07 introduces some changes and challenges that developers need to be aware of when integrating it into their projects. If you’re upgrading to or configuring Room Alpha-07, here’s a guide to help you through the process, complete with code snippets.</p><h3>Step 1: Handling the Room Plugin</h3><p>In the Alpha-07 version, the Room plugin may not work as expected. As a workaround, you can temporarily disable it in your project configuration:</p><pre><br>// TODO add plugin back in when this is supported again<br>// alias(libs.plugins.room)</pre><p>By commenting out the plugin, you can avoid potential issues that might arise during the build process.</p><h3>Step 2: Configuring KSP for Room Schema Location</h3><p>Room requires a schema location to generate schema files. Since the plugin is currently disabled, you can use Kotlin Symbol Processing (KSP) to specify the schema location:</p><pre>ksp {<br> arg(“room.schemaLocation”, “${projectDir}/schemas”)<br>}</pre><p>This configuration tells KSP where to place the Room schema files, ensuring they are correctly generated during the build.</p><h3>Step 3: Adding Room Compiler Dependencies</h3><p>To ensure that Room works across different platforms (Android and iOS), you need to add the Room compiler dependencies manually. Here’s how you can do it:</p><pre>dependencies {<br> listOf(<br> “kspAndroid”,<br> “kspIosSimulatorArm64”,<br> “kspIosX64”,<br> “kspIosArm64”<br> ).forEach {<br> add(it, libs.androidx.room.compiler)<br> }<br>}</pre><p>This snippet iterates over the different platforms and adds the necessary Room compiler dependencies for each one, ensuring compatibility across your project.</p><h3>Step 4: Future-proofing for the Room Plugin</h3><p>Since the Room plugin might be fixed or updated in future versions, it’s a good idea to leave reminders in your code to re-enable the plugin and schema configuration when it becomes stable:</p><pre>// TODO renable room plugin when it works properly<br>//room {<br>// schemaDirectory(“$projectDir/schemas”)<br>//}</pre><p>By leaving these comments in your code, you ensure that future maintenance or upgrades will be easier, as you won’t need to remember the specifics of what was disabled.</p><p>This allows you to maintain a clean and modular approach to initializing your database, accommodating any platform-specific needs.</p><h3><strong>Step 5: Configuring App Database Constructor</strong></h3><p>Finally, when setting up the database, you’ll want to define a platform-specific implementation of the Room database constructor. This can be done using the following snippet:</p><pre>expect object AppDatabaseConstructor : RoomDatabaseConstructor&lt;AppDatabase&gt;</pre><p>This allows you to maintain a clean and modular approach to initializing your database, accommodating any platform-specific needs.</p><h3><strong>Conclusion</strong></h3><p>Configuring Room Alpha-07 requires a few extra steps due to the current limitations of the plugin. However, by carefully managing your dependencies, using KSP for schema generation, and properly configuring the AppDatabaseConstructor, you can maintain a stable and functional project. As always, keep an eye on future updates to Room and revisit the commented-out sections when the plugin is fully supported again.</p><p>This guide should help you get Room Alpha-07 up and running smoothly in your project. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53da35074ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segmented Buttons Compose Material 3]]></title>
            <link>https://medium.com/@fergus.a.hewson/segmented-buttons-compose-material-3-8d64e94989e1?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d64e94989e1</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[material3]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 02:45:15 GMT</pubDate>
            <atom:updated>2023-10-06T02:47:00.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>If you have delved into the world of <strong>JetpackCompose </strong>(Compose) and <strong>Material3</strong> (M3) you would have come across the amazing website <a href="https://m3.material.io/">Material3.io</a>, where all of the available components are specified in great detail. Each component has an <strong>Overview</strong> of how the component should be used, detailed <strong>Specifications o</strong>n the how the component should look<strong>, Guidelines </strong>for usage and an<strong> Accessibility </strong>guide for it’s use for impaired users. It is beautiful website that goes into great detail and making it an excellent resource for developers/designers when starting their <strong>M3</strong> journey.</p><p>In a <a href="https://medium.com/@fergus.a.hewson/material-design-2-vs-3-an-assessment-apparatus-f7bed5770a50">previous article</a> an <strong>Assessment Apparatus </strong>was detailed,<strong> </strong>providing a mechanism for evaluating the <strong>M3</strong> library. A <strong>ComponentMash</strong> was used, where all of the components in the library were put on a page for developers/designers to look over, set the <strong>ColorScheme</strong> and decide what components to use in the App. There was one component missing, the <strong>SegmentedButtons</strong>, a crucial aspect to the App we were developing. It’s omission was very curious since the designers could find in the <strong>Figma</strong> sheet provided by <strong>Google</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lvdsD7uEX7fTd9LJ9ojSw.png" /><figcaption>M2 vs M3 SegmentedButtons design. Source <a href="https://m3.material.io/components/segmented-buttons/overview#97f408eb-1e19-493f-919f-027b1ae9da00">https://m3.material.io/components/segmented-buttons/overview#97f408eb-1e19-493f-919f-027b1ae9da00</a></figcaption></figure><p>The <strong>SegmentedButtons</strong> was defined in the <strong>M3</strong> specification, but was no where to be found in the <strong>Compose</strong> library. After a quick read of the specification we found a section called <strong>Resources</strong>, which explained the state of development for the component in all the different libraries that implemented the <strong>M3</strong> specification. The <strong>SegmentedButtons</strong> had the status <strong>Available</strong> in <strong>Figma</strong>, but planned in <strong>Jetpack Compose, </strong>showing us why the component was not <strong>Available</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbj_z7yEQE-cW5Yuf6oqEA.png" /><figcaption>Segmented buttons status across all resources. Source <a href="https://m3.material.io/components/segmented-buttons/overview#0788e20e-6062-408d-bf51-521be9bc5593">https://m3.material.io/components/segmented-buttons/overview#0788e20e-6062-408d-bf51-521be9bc5593</a></figcaption></figure><h3>Choices</h3><p>As a team, we had two choices.</p><ol><li>Find another <strong>Component</strong> that meet some of our requirements until the <strong>M3 Compose </strong>library was updated.</li><li>Build our own.</li></ol><p>We decided to bite the bullet and have a crack at building it ourselves. The rest of the post will how the component was developed and the software design choices used during development.</p><h3><strong>Implementation</strong></h3><p>First things, first. We needed to define what the component was.</p><ul><li>Bordered <strong>RoundedCorner</strong> component</li><li><strong>Dividers</strong> between each of the items.</li><li>A series of <strong>Text</strong> and <strong>Icons</strong> that were clickable and had different states based on selected state.</li><li>Offers <strong>Single-Select</strong> or <strong>Multi-Select</strong> functionality with an indicator for selected items.</li><li>Design a simple <strong>API</strong> for developers to use</li></ul><p><strong>Simple Problems</strong></p><p>A full <strong>RoundedCorner</strong> component is very easy to implement using <strong>Compose</strong>. A typical mechanism is to pass in a <strong>Shape</strong> into the <strong>Composable</strong> with a default set to a <strong>RoundedCornerShape</strong> of 50 percent.</p><p>Adding a <strong>Border</strong> is very simple too, pass in the the required <strong>OutlineThickness</strong> and the <strong>BorderStroke</strong> you want to apply, with the defaults required for the component.</p><p>Pass the <strong>Shape</strong> and <strong>Border</strong> to a root <strong>Surface</strong> <strong>Composable</strong> and we are good to go.</p><pre>@Composable<br>fun SegmentedButtons(<br>    modifier: Modifier = Modifier,<br>    shape: Shape = RoundedCornerShape(percent = 50),<br>    colors: SegmentedButtonColors = SegmentedButtonsDefaults.colors(),<br>    outlineThickness: Dp = SegmentedButtonsDefaults.outlineThickness,<br>    border: BorderStroke = BorderStroke(outlineThickness, colors.outlineColor),<br>    content: @Composable () -&gt; Unit){<br><br>    Surface(<br>        shape = shape,<br>        border = border,<br>        modifier = modifier.defaultMinSize(minHeight = minimumHeight)<br>    ) {}<br>}</pre><h4><strong>Difficult problems</strong></h4><p>Designing the <strong>API</strong> and the adding content to the <strong>SegmentedButtons</strong> seemed simple on the surface. Pass in the <strong>Text/Icons</strong> and <strong>Dividers</strong> and we are done!</p><pre>SegmentedButtons {<br>    Text(text = &quot;A&quot;)<br>    Divider()<br>    Text(text = &quot;B&quot;)<br>    Divider()<br>    Text(text = &quot;C&quot;)<br>    Divider()<br>}</pre><p>However, this does not meet the requirement of a simple <strong>API</strong> for developers to use, it also has layout problems and doesn’t scale well with different size content. There are many ways to over come this with defaults, but we wanted a polished component that was similar to the ones provided by Google.</p><p>Adding an <strong>Indicator</strong> based on the selected <strong>Items</strong> was not possible using this <strong>API</strong> either. We wanted the <strong>Component</strong> to handle this and not have clients of the <strong>API</strong> have to worry about these things.</p><h4>Look for inspiration</h4><p>There we two other components that offered similar functionality in the <strong>Compose</strong> <strong>M3</strong> library.</p><ul><li><strong>TabRow</strong> — simple <strong>API</strong> and <strong>Indicator</strong> that highlighted the selected item</li><li><strong>NavigationBar</strong> — Similar to <strong>TabRow</strong> but had styling based on the selected item.</li></ul><p>Looking at the <strong>TabRow</strong>, it uses a <strong>SubcomposeLayout</strong> to layout the content before hand and then place.</p><blockquote>Analogue of Layout which allows to subcompose the actual content during the measuring stage for example to use the values calculated during the measurement as params for the composition of the children.</blockquote><p>This allows the <strong>TabRow</strong> to <strong>Compose</strong> it’s content and then layout the children based on it’s own requirements, in the case with an even width and spacing for the <strong>Tabs</strong>. The call to <strong>subcompose</strong> inside a <strong>SubcomposeLayout</strong> returns a list of <strong>Measurables</strong> which is then used to calculate the width based on the number of <strong>Tabs</strong> and the width of the contraints of the parent <strong>Layout</strong>.</p><pre>SubcomposeLayout(Modifier.fillMaxWidth()) { constraints -&gt;<br>            val tabRowWidth = constraints.maxWidth<br>            val tabMeasurables = subcompose(TabSlots.Tabs, tabs)<br>            val tabCount = tabMeasurables.size<br>            var tabWidth = 0<br>            if (tabCount &gt; 0) {<br>                tabWidth = (tabRowWidth / tabCount)<br>            }</pre><p>After the <strong>subcompose</strong> the <strong>measureables</strong> are measured and returned as <strong>Placeables</strong> to be placed in the call to Layout.</p><pre>val tabPlaceables = tabMeasurables.map {<br>    it.measure(<br>        constraints.copy(<br>            minWidth = tabWidth,<br>            maxWidth = tabWidth,<br>            minHeight = tabRowHeight,<br>            maxHeight = tabRowHeight,<br>        )<br>    )<br>}</pre><p>The <strong>TabRow</strong> does provide an example for placing <strong>dividers</strong> too, this can be seen in the call to <strong>layout</strong>. We also have a fantastic example for how to place an <strong>indicator</strong> behind the selected <strong>Tab</strong>.</p><pre>layout(tabRowWidth, tabRowHeight) {<br>    tabPlaceables.forEachIndexed { index, placeable -&gt;<br>        placeable.placeRelative(index * tabWidth, 0)<br>    }<br><br>    subcompose(TabSlots.Divider, divider).forEach {<br>        val placeable = it.measure(constraints.copy(minHeight = 0))<br>        placeable.placeRelative(0, tabRowHeight - placeable.height)<br>    }<br><br>    subcompose(TabSlots.Indicator) {<br>        indicator(tabPositions)<br>    }.forEach {<br>        it.measure(Constraints.fixed(tabRowWidth, tabRowHeight)).placeRelative(0, 0)<br>    }<br>}</pre><p>It seems we have all we need to do the bulk of the heavy lifting to construct our <strong>SegmentedButtons</strong>. However, we are missing a core aspect of the spec, different <strong>Colors</strong> and <strong>Typography</strong> for the selected <strong>Item</strong>. This is where we need to look at the <strong>NavigationBar</strong> which does exactly that.</p><p>Also, implementing <strong>MultiSelect</strong> would be very difficult using this pattern, we would need to have multiple indicators for each selected item and pass in set of selected items into the <strong>SegmentedButtons</strong> making the <strong>API</strong> fare more cumbersome.</p><p>The <strong>API</strong> for the <strong>NavigationBar</strong> is significantly different, the core of the composable is a simple row with lays out the different <strong>NavigationBarItem</strong> separately. If we copied this pattern we would not be able to implement the dividers as required for the <strong>SegmentedButtons</strong>. The real havy lifting is done by the <strong>Item</strong> itself.</p><p>The opening lines of the <strong>NavigationBar</strong> items demonstrates the functionality of styling the <strong>Icon</strong> and the <strong>Label</strong> based on the <strong>Selected</strong> state of the <strong>Item</strong>, solving a big problem for our <strong>SegmentedButtons</strong> component.</p><pre>val styledIcon = @Composable {<br>    val iconColor by colors.iconColor(selected = selected, enabled = enabled)<br>    // If there&#39;s a label, don&#39;t have a11y services repeat the icon description.<br>    val clearSemantics = label != null &amp;&amp; (alwaysShowLabel || selected)<br>    Box(modifier = if (clearSemantics) Modifier.clearAndSetSemantics {} else Modifier) {<br>        CompositionLocalProvider(LocalContentColor provides iconColor, content = icon)<br>    }<br>}<br><br>val styledLabel: @Composable (() -&gt; Unit)? = label?.let {<br>    @Composable {<br>        val style = MaterialTheme.typography.fromToken(NavigationBarTokens.LabelTextFont)<br>        val textColor by colors.textColor(selected = selected, enabled = enabled)<br>        CompositionLocalProvider(LocalContentColor provides textColor) {<br>            ProvideTextStyle(style, content = label)<br>        }<br>    }<br>}</pre><p>If we merge these two styles of components we can achieve the desired effects of <strong>MultiSelect</strong>, styling selected <strong>Items</strong> and a nice clean <strong>API</strong> for Developers to use.</p><h4>Full implementation</h4><p>I will not go over the full implementation of the <strong>SegmentedButtons</strong> component, but you can find it here in the this <strong>Gist</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7159011446fee69c3bba3727f198fa/href">https://medium.com/media/4c7159011446fee69c3bba3727f198fa/href</a></iframe><p>The usage of this <strong>API</strong> is extremely clean and powerful allowing developers to use this component with a great deal of customisation and all of the heavy lifting done for them.</p><pre>SegmentedButtons {<br>    SegmentedButtonItem(<br>        selected = selectedIndex == 0,<br>        onClick = { selectedIndex = 0 },<br>        label = { ItemText(text = &quot;Alpha&quot;, textVisible = textVisible) },<br>        icon = { ItemIcon(icon = R.drawable.ic_terms_conditions, iconsVisible) }<br>    )<br>    SegmentedButtonItem(<br>        selected = selectedIndex == 1,<br>        onClick = { selectedIndex = 1 },<br>        label = { ItemText(text = &quot;Bravo&quot;, textVisible = textVisible) },<br>        icon = { ItemIcon(icon = R.drawable.sg_icon_delete_blue_24dp, iconsVisible) }<br>    )<br>    SegmentedButtonItem(<br>        selected = selectedIndex == 2,<br>        onClick = { selectedIndex = 2 },<br>        label = { ItemText(text = &quot;Charlie&quot;, textVisible = textVisible) },<br>        icon = {<br>            ItemIcon(<br>                icon = R.drawable.sg_icon_change_payment_blue_24dp,<br>                iconsVisible<br>            )<br>        }<br>    )<br>}</pre><p><strong>MultiSelect</strong> can easily be implemented through this <strong>API</strong>. Simply have a set of selected indices remembered in the composition and set the <strong>SelectedState</strong> of the item based on this set. This would not be possible with an <strong>API</strong> like the the <strong>TabRow</strong>.</p><h4>Future work</h4><p>We have not implemented the <strong>Disabled</strong> state as required in the <strong>M3</strong> specification. This was not needed at time of development, but if implemented in the future another article will be written on the mechanisms used to implement it.</p><h4>Conclusion</h4><p>This was a fun component to build. Exploring different components in the <strong>M3</strong> library and merging different concepts together was a great learning experience. We have covered subcompose, styling based on different states and developing a clean <strong>API</strong> for other developers to use.</p><p>I really hope this is a valuable blog post to someone and they get great value out of this work.</p><p>Thanks for reading and Happy-Composing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d64e94989e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Material design 2 vs 3 - an assessment apparatus]]></title>
            <link>https://medium.com/@fergus.a.hewson/material-design-2-vs-3-an-assessment-apparatus-f7bed5770a50?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7bed5770a50</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 22:35:57 GMT</pubDate>
            <atom:updated>2023-09-30T22:35:57.428Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Intro</strong></h3><p>In the 7 years since Google released it’s Material Design palette, the state of User Interface (UI) design has developed significantly. In 2021 Material 3 was announced to connect with the new state of play. Coincidentally, this has aligned with the released of Jetpack compose, a modern UI Toolkit for the Android community. The duality of these changes has left teams with an Multiple Migration problem, how to incorporate these 2 changes into their Applications over the next few years.</p><h3>Material story</h3><p>Material Design was developed by Google, as a visual language that could bridge the divide between developers and designers. Released in 2014, it provided developers with a set of out-of-box design principals which they could crudely design Apps which looked half decent, whilst avoiding the Magenta and Cyan colours which plague dev-UI practices. It is also gave a designers a box with which they could play in, containing the foundations of the platforms look and feel, but with a dash of flair and customization that appeals to their thinking tenor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*40s9grn6sYz3ZVuPrOz0Eg.png" /><figcaption>Material Design : source Wikipedia.</figcaption></figure><p>In 2021, at Google I/O, a new concept was announced, Material You or Material 3 (M3). It emphasised audacious animations, larger buttons, distinct elevation panes and custom UI themes based on the users wallpaper. This is was not an overhaul of the Material design system it was a modernisation, a refresh and an update for the direction UI design had taken in the 7 years since Material was released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eTxDuUkbwO2oXG6powWVvQ.png" /><figcaption>Material You (3) : source Wikipedia.</figcaption></figure><p>Alongside the UI design changes, Jetpack Compose (Compose) was released in July 2021, as modern UI Kit for building native Android applications. XML was replaced with a functional reactive framework written entirely in Kotlin, allowing Developers to think in the same language throughout out their Application space. Now, in 2023, Compose has been adopted as the industry standard and most tech companies have begun their migration from XML to Compose.</p><h3>Multiple Migrations</h3><p>Coupling the release of Compose with the Google’s updated Material framework has left Android developers with a tough decision and easy decision with respect to the Multiple Migrations in their application space.</p><blockquote>XML -&gt; Compose</blockquote><p>A purely technological transformation, replacing each screen with a different underlying technology set. As if moving from a internal combustion engine to electrical engine in your motor vehicle, whilst the steering wheel and break pedals act much the same, but with a drastically different engine noise.</p><blockquote>M2 -&gt; M3</blockquote><p>A conscious transformation of how the user interacts with the application. The underlying technology set might be the same (XML), however we are looking at completely different steering wheel, with throttle-esq mechanism to manage velocity variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*u3NXdfPkkRcPwXhnW53Hgg.jpeg" /><figcaption>M2/M3 a metaphor. Source autonews.com</figcaption></figure><h3>Assessment Apparatus</h3><p>Facing down this Multiple Migration situation at my work, we had to make tough decisions on how to manage this problem same. Not only were there Technical/Design considerations of the Application Structure. Now a human factor came into play, there was a conflicting perspectives between Developer/Design space and again a the omnipresent spectrum of developer perspectives.</p><blockquote><em>Developers</em></blockquote><ul><li>Dev’s wanted compose, the migration had begun, 5 % of the code base was migrated to compose and the in house UI Toolkit was being migrated component by component. This was happening!</li><li>M2/M3 was different, many Developers could not see a significant enough difference in the look of M3 to warrant the extra work. Some were concerned with the freshness of the M3 library, there were @ExpiermentalM3Api annotations littered throughout the M3 code, and many of the API’s had already been deprecated in the libs short lifetime. This signified risks of managing a changing API.</li></ul><blockquote>Designers</blockquote><ul><li>Designers were confused at the state of play. Was M2 something that would be around for a long time? Would M3 come along at some point and make their designs defunct? How would they plan out their Design components for the App refresh over the next year? Would the refresh be done again in a year when the M3 migration was Green-Lighted?</li><li>A slight concern was voiced, that of having different screens having a different look and feel during the migration. However, as you might notice in the screen shots above, the differences are not significant enough to stop the M3 migration.</li><li>With respect to Compose, Designers could care less what Developers used for their UI Toolkit, as long as the delightful designs were expressed on screen ❤</li></ul><blockquote>Options</blockquote><p>In short, compose was happening, would M3 happen at the same time? Trade off’s needed to be evaluated. Here were the two options…</p><ol><li>Migrate to Compose now and do M3 later. Less risk from a developer perspective, we could use stable API’s in the future and the learnings from the Compose migration to handle the M3 migration with greater competitance. However, this is would incur more tech-debt, more knowledge-debt and increase designer frustration.</li><li>Do both migrations at once. Compose was fresh and migrating now would cost significantly less in the future. However this would require more learning upfront from bother Developers and Design, and more risk with unstable API’s.</li></ol><p>From a empirical perspective, here is the equation that needed to balanced</p><blockquote>M2TD + M2KD &lt; M3IC + M3R</blockquote><ul><li>M2TD = Tech debt incurred from remaining on M2</li><li>KD = Knowledge debt incurred by remaining on M2</li><li>M3IC = Cost of migrating to M3 immediately</li><li>M3R = Risk from Migrating to M3 with unstable API’s</li></ul><blockquote>Was the cost of Moving to M3 less than the cost of staying on M2?</blockquote><p>Each company/situation will apply different weights to these values and come out with a completely different answer. Each weighting is very subjective leaning to a very difficult decision if one of the parameters did not dominant the equation in your specific perspective.</p><p>Our results was that the cost of Tech-Debt/Knowledge-Debt incurred would be significantly higher than the upfront cost of moving to M3 immediately, so we decided to<em> Rip The Band-Aid</em> off and embrace M3 immediately.</p><h3>Evaluation epilogue</h3><p>In evaluating the M3, Designers wanted to see the complete palette of widgets on offer in the Library and how the set color schemes would affect their Look-and-Feel.</p><p>A technique we used was to Mash every single component from the M3 library onto a single, showcasing the whole library to both Developers and Design. Developers could see the breadth of the experimental API’s and designers could go shopping, taking what widgets they liked and leaving the rest out of their Design ToolKit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*as_NTixI3M0iB8rfx9Napw.gif" /><figcaption>The M3 Component Mash.</figcaption></figure><p><a href="https://gist.github.com/fergdev/b8255a604b0521c3d0701f8a3733742d">Here </a>is a link to the component Mash if you would like to use it in your evaluation of the M3 compose Library.</p><h3>Conclusion</h3><p>Many Android tech teams are facing into the problem of managing the Multiple Migrations from XML-&gt;Compose and M2-&gt;M3 at the moment. There are many factors at play Technical, Design and Human. All of these need to be balanced whilst making the decision on what to migrate and when. Hopefully I helped making this decision easier for teams facing into this complex scenario.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7bed5770a50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intellij Live Templates for Comfy Composing]]></title>
            <link>https://medium.com/@fergus.a.hewson/intellij-live-templates-for-comfy-composing-7c7e9a69d377?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c7e9a69d377</guid>
            <category><![CDATA[intellij-idea]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 00:09:39 GMT</pubDate>
            <atom:updated>2023-09-24T00:09:39.885Z</atom:updated>
            <content:encoded><![CDATA[<p>Intellij Live templates (LT) are great way to speed up the mundane aspects of software development. Recently I have delved deep into the world of Jetpack Compose and have rediscovered the LT as a mechanism to remove some of the common blockers to a smooth development workflow.</p><p>Leveraging LTs would have been possible for XML, but tedious because it is not the language I am most versed in writing. With Compose/Kotlin we can bring all the tooling available to bare on the different pain points we have when developing views!</p><p>Android studio comes bundled with LTs to help you write Compose code. These were a great inspiration for me to develop my own set of templates.</p><p>To find the bundle LTs in Intellij go</p><blockquote>Preference -&gt; Editor -&gt; Live Templates -&gt; AndroidCompose</blockquote><p>Or for actions searchers…</p><blockquote>CMD + SHFT + A -&gt; Live Templates -&gt; AndroidCompose</blockquote><h3>Bundled LTs — create @Composable function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kybKtFUvYoIACKREqjdrrA.gif" /><figcaption>comp live template</figcaption></figure><p>This is by favourite bundled LT. Lets you write the scaffold of a compose function extremely quickly. Simply type <em>comp </em>into the editor a press<em> Enter </em>and let the LT will fill out the scaffold of a Composable for you<em>. </em>All that is left to do is type out the name and start developing the body of the function.</p><p>Let’s delve into the code for the LT.</p><pre>abbrev = comp<br><br>@androidx.compose.runtime.Composable<br>private fun $NAME$() {<br>$END$<br>}</pre><p>Things to note.</p><ol><li>The Composable reference has a fully qualified class name, which is super handy when you haven’t imported this annotation yet! With out this your LT workflow will include having to import this function before you start developing the body of the Composable.</li><li>You can set parameters to fill in along the way, in this case the $NAME$ parameter is for the name of the Composable.</li><li>$END$ is where you want your cursor positioned after you have finished typing. In this case we want to start developing the body of the Composable so we put it in the body of the function.</li><li>abbrev is the abbreviation the editor will use when you are coding. In this example, simply type <em>comp</em> and press <em>enter</em> to invoke the LT.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*lpRzOJ2FPiz-yqr1wClSxg.png" /><figcaption>Options for the comp LT</figcaption></figure><p>Options are super important when specifying the LT. Definitely take advantage of tooling here and let the IDE reformat and shorten your class names so you can move on quickly to writing the next part of your UI.</p><h3>Custom LTs</h3><p>Now we get to be create, analyse our own workflow and think of new ways to do things faster!</p><p>So far, I have 4 main areas where I use LTs to speed up my compose development! Hopefully I will develop more as I progress further down the compose journey.</p><ol><li>Composable from scratch</li><li>Layout from selected</li><li>Widgets</li><li>Modifiers / parameters.</li></ol><h3>Layout from scratch</h3><p>These are LTs are very similar to the original comp LT that was analysed above. They insert a layout Composable and place the cursor in the a nice position to continue developing your layout quickly.</p><p>They are the bread and butt of layouts in Compose.</p><pre>abbrev = box<br><br>androidx.compose.foundation.layout.Box {<br>    $END$<br>}</pre><pre>abbrev = colm<br><br>androidx.compose.foundation.layout.Column {<br>    $END$<br>}</pre><pre>abbrev = row<br><br>androidx.compose.foundation.layout.Row {<br>    $END$<br>}</pre><p>I have not made LTs for LazyRow and LazyList because I do not use them that often when writing compose functions, the overhead of making an LT for them is not worth it for me right now and writing them for seems like a premature optimization for me.</p><blockquote>Spend your time developing code, not Live Templates</blockquote><p>I usually only develop LTs when I am very sick of typing something out over and over again!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Gs7H_S7Lad2BO1poZ_P2uQ.gif" /><figcaption>Demo for comp/box/colm/row</figcaption></figure><p>Quick gotcha: make sure you specify the scope where you want the LT to able to be invoked from. If you don’t fill this out, you will be left wondering why your LT is not available in the code completion window.</p><p>Check the provided Comp LT for Google’s guidance (they only exclude comments). I like to set the most limited set possible and expand it when I find a use case that my LT does not work in I add it to the scopes (this is to help me learn as well, I’m sure the more expansionist policy is fine here too).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*n1Mg0sEuGlw6IHmdZIVzEw.png" /><figcaption>LT scopes, my preferences.</figcaption></figure><h3>Layout from selected</h3><p>A powerful mechanism of LTs is to take selected text and apply an LT to it. The one area you can make great time savings is when you have developed a composable block that needs to wrapped in a box/col/row/card for padding, background or something else that has skipped your mind.</p><p>LTs use the variable $SELECTION$ to denote the block of text that was selected when the LT was invoked. Below is my definition of an LT to wrap a block of code in a Compose Box.</p><pre>abbrev = boxsel<br><br>androidx.compose.foundation.layout.Box $END$ {<br>    $SELECTION$ <br>}</pre><p>Note how I have placed the $END$ variable after the Box, this allows me to start writing the parameters of the Box straight away (modifier, layout ..ect). One improvement is to place the cursor inside brackets here, so I don’t have to type that each time, I might change this in my LT workflow soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*iOkyV2J-BwRkEp_1bG-Asg.gif" /><figcaption>Adding padding to icon using selection LT.</figcaption></figure><p>To invoke a selection-based LT</p><ol><li>Make a selection (in the above gif I use IdeaVim select line <em>Shift+J</em>)</li><li>Press <em>CMD+ALT+J</em></li><li>Start typing the abbreviation, often the first letter is good enough.</li></ol><p>Here are the other Selection based LTs I currently use.</p><pre>abbrev = colsel<br><br>androidx.compose.foundation.layout.Column $END$ {<br>    $SELECTION$<br>}</pre><pre>abbrev = ecsel<br><br>androidx.compose.material3.ElevatedCard $END$ {<br>    $SELECTION$ <br>}</pre><pre>abbrev = rowsel<br><br>androidx.compose.foundation.layout.Row $END$ {<br>    $SELECTION$<br>}</pre><h3>Widgets</h3><p>There are many widgets that you make over and over again when developing Compose layouts. Here is my current list of widget LTs.</p><p>M3 Button: let’s you write the onClick function and then move straight to the body of the Button.</p><pre>abbrev = butt<br>androidx.compose.material3.Button(onClick = {$ONCLICK$}){<br>    $END$<br>}</pre><p>M3 Icon: with a variable where you want to specify the image vector.</p><pre>androidx.compose.material3.Icon(imageVector = $V$, contentDescription = null)</pre><p>M3 Text: with a variable to write the display text.</p><pre>androidx.compose.material3.Text(text = &quot;$TEXT$&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JnLjlDCdGLqJp_rMe6NSDg.gif" /><figcaption>Text Widget LT example.</figcaption></figure><p>Note: all of these are for Material3, make sure the import works for you if you are using M2 :).</p><p><strong>Modifiers / Parameters</strong></p><p>Lastly I use LTs to quickly write modifiers and parameters for different Composables.</p><p>Typing out Modifier, finding the right type and getting the import correct, is was one of the biggest pain points for me when Composing. This is now solved for me in my workflow by LTs. See the gif above for usage when setting the padding on the Box.</p><pre>abbrev = modi<br><br>modifier = androidx.compose.ui.Modifier.$END$</pre><p>The other two major pain points in my Compose workflow were typing out SpacedBy for vertical and horizontal arrangement. Here are the LTs I use to solve this problem</p><pre>abbrev = sbh<br><br>horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy($DP$)</pre><pre>abbrev = sbv<br><br>verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy($DP$)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jbadWPTdDTXBAi-m5NOk9A.gif" /><figcaption>Spaced by vertical LT</figcaption></figure><h3>Wrap up</h3><p>Live Templates are awesome! They speed up your coding experience, reduce pain points and make for a comfier developer experience.</p><p>Now with Compose/Kotlin we can leverage their full power when developing Views! The days of XML are truly over :)</p><p>Have a play for yourself, find common pain points in your workflow, think about ways to improve it and develop an LT to get smooth over these bumps. Rinse and repeat until you can let the code fly from your finger tips.</p><p>Share your experiences with other dev’s so we all can improve our developer experience!</p><p>Happy Composing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c7e9a69d377" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose Ripple Customisation Guide]]></title>
            <link>https://medium.com/@fergus.a.hewson/compose-ripple-customisation-guide-5cb11e4ad876?source=rss-fe3762fb29c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb11e4ad876</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Fergus A Hewson]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 00:27:56 GMT</pubDate>
            <atom:updated>2023-09-23T22:19:40.484Z</atom:updated>
            <content:encoded><![CDATA[<p>This week at work, I was tasked to style ripples for the new Compose screens!</p><p>Design wanted a default style and 4 overridable styles to use in different contexts throughout the App.</p><blockquote>DEFAULT, RED, BLUE, REG, ORANGE</blockquote><p>The first solution that came to mind was using a custom <strong>Indication</strong> to change the ripple color!</p><pre>Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {<br>    Box(<br>        modifier = Modifier<br>            .size(200.dp, 200.dp)<br>            .border(2.dp, Color.Black)<br>            .clickable(<br>                interactionSource = remember { MutableInteractionSource() },<br>                indication = rememberRipple(color = Color.Red),<br>                onClick = { /* wooo*/ }<br>            )<br>    )<br>    {}<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*chsrWeWoa0dRrkC9OgcjfQ.gif" /></figure><p>Easy! Then off to make it reusable by making a custom <strong>Modifier</strong> that accepts a color as the arguments…</p><pre>fun Modifier.clickWithRedRipple(color: Color, onClick: () -&gt; Unit): Modifier = composed {<br>    this.clickable(<br>        interactionSource = remember { MutableInteractionSource() },<br>        indication = rememberRipple(color = color),<br>        onClick = onClick<br>    )<br>}</pre><p>Now we can specify what ever Ripple color we like as a modifier on a composable!</p><pre>.clickableWithRipple(Color.Red) { /* woosh */ }<br>.clickableWithRipple(Color.Green) { /* woosh */ }<br>.clickableWithRipple(Color.Blue) { /* woosh */ }<br>.clickableWithRipple(Color.Magenta) { /* woosh */ }</pre><p>Happy as, I trot off to design to show them my work, thinking this was an easy win for the team!</p><p>However, they required <strong>DARKER</strong> Ripples!</p><p>Back I trot, to the drawing board!</p><p>With no obvious way to increase the Alpha on the <strong>Indicator</strong> Ripple I was stumped.</p><p>After some digging I discovered the <strong>RippleTheme</strong> and how it could be used with <strong>CompositionLocalProvider </strong>to change the Ripple Color/Alpha.</p><p>So I made a <strong>RippleTheme</strong> with full <strong>RippleAlpha.</strong></p><pre>@Immutable<br>object RedRipple : RippleTheme {<br>    @Composable<br>    override fun defaultColor() = Color.Red<br><br>    @Composable<br>    override fun rippleAlpha(): RippleAlpha = RippleAlpha(1f, 1f, 1f, 1f)<br>}<br></pre><p>Then wrapped my clickable with a <strong>CompositionLocalProvider </strong>that provided the full Alpha<strong> RippleTheme.</strong></p><pre>CompositionLocalProvider(LocalRippleTheme provides RedRipple ) {<br>    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {<br>        Box(<br>            modifier = Modifier<br>                .size(200.dp, 200.dp)<br>                .border(2.dp, Color.Black)<br>                .clickable { /* woosh */ }<br>        ){}<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*VQvgyba5gRBem_oZ5KTCKw.gif" /><figcaption>Darker red ripple.</figcaption></figure><p>Woohoo! Full Red-Ripple! Well … as full as you can get till the RippleDrawable clamps the Alpha on you … I found this little gem in the material ripple library that explains it all.</p><pre>RippleHostView.android.kt : 380 : material-ripple:1.4.1@aar<br>// Note: above 28 the ripple alpha is clamped to 50%, so this might not be the<br>// _actual_ alpha that is used in the ripple.</pre><p>Now we have maxed out the alpha but at the expense of boilerplate and the cool reusable pattern of <strong>Modifier</strong> extensions functions.</p><p>Determined to keep a clean pattern and interested to see why the <strong>Indicator</strong> Ripple was lighter … I dug in to the Material Ripple code and found the Alpha on the Ripples generated from the <strong>Indicator</strong> pattern was extracted from the <strong>RippleTheme</strong> provided in the <strong>CompositionLocalProvider</strong>.</p><pre>Ripple.kt : 125 : material-ripple:1.4.1@aar<br><br>val theme = LocalRippleTheme.current<br>val color = rememberUpdatedState(<br>    if (color.value.isSpecified) {<br>        color.value<br>    } else {<br>        theme.defaultColor()<br>    }<br>)<br>val rippleAlpha = rememberUpdatedState(theme.rippleAlpha())</pre><p>Idea … If we provide a <strong>RippleTheme</strong> at the root of the <strong>MaterialTheme</strong> with full Alpha we will get full Alpha whilst using the <strong>Indicator</strong> pattern. Allowing us to get rid of the <strong>LocalCompositionProvider</strong> boiler plate!!!</p><p>Here is the full Alpha ripple which is copied from the <strong>MaterialRipple</strong> … but with the Alpha at 100!</p><pre>@Immutable<br>object FullAlphaRipple : RippleTheme {<br>    @Composable<br>    override fun defaultColor() = LocalContentColor.current<br><br>    @Composable<br>    override fun rippleAlpha(): RippleAlpha = RippleAlpha(1f, 1f, 1f, 1f)<br>}</pre><p>Next to provide our ripple in the <strong>MaterialTheme</strong>…</p><pre>MaterialTheme(<br>    colorScheme = colorScheme,<br>    typography = Typography,<br>) {<br>    CompositionLocalProvider(LocalRippleTheme provides FullAlphaRipple) {<br>        content()<br>    }<br>}<br>// Please don&#39;t use this code, it misses a lot of setup that is in the MaterialTheme<br>// Look into the material theme and see all the differen providers that you will miss out on.<br>// If you do this, make sure you provide ALL-THE-THINGS the material theme does.<br>// This is just a brief example!</pre><p>There we have it! Now our <strong>Indicator/Modifier</strong> pattern will work with full alpha anywhere in the App, saving boiler plate and making developers lives easier!</p><p>Note: this will turn up the Alpha on all your Ripples too! Beware!</p><p>This works for both Material 2/3!</p><p>Happy Composing :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb11e4ad876" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>