Home > database >  Enable Compose Compiler in KMM Module
Enable Compose Compiler in KMM Module

Time:08-04

I'm working on a KMM project and ran into this article while working on improving performance https://www.jetpackcompose.app/articles/how-can-I-debug-recompositions-in-jetpack-compose

My shared KMM module has a lot of data classes that are used in the UI and the section at the end of the article caught my attention.

If you are using classes from modules that don't have compose enabled, the compose compiler won't be able to infer their stability

I have a composable that takes in a data class from the shared module and displays the data similar to the article. Using the Compose debug tools, I was able to confirm that the composable wasn't marked as skippable and the data class was marked with unstable

I followed the second workaround they provided wrapping the data class in another data class in the Android module and it worked to mark it as stable and skippable.

Instead of cluttering my app with tons of wrapper classes, I'd love to use their first around.

  1. Add compose support to the module that has the data class

My question is how do you enable compose support for the shared portion of a KMM app?

I've tried enabling the plugin with the following.

plugins {
  id("org.jetbrains.compose") version "1.2.0-alpha01-dev753"
}

However, I can't get Gradle to resolve the plugin.

I don't see a place to do it the "normal" way of setting compose to be true like in the Android build.gradle.kts file.

android {
...
    buildFeatures {
        // Enables Jetpack Compose for this module
        compose = true
    }
...
}

Is there a way to add to buildFeatures in the shared module?

CodePudding user response:

I was able to get this to work.

First, in the shared build.gradle.kts file, make these changes.

android {
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = "1.2.0"
    }
}

kotlin {
    ...
    sourceSets {
        ...
        val androidMain by getting {
            dependencies {
                implementation("androidx.compose.runtime:runtime:1.3.0-alpha02")
                ...
            }
        }
    ...
    }
}
  

Make sure the compiler version is the same as in your Android module's build file.

Then create a file and add an expect for the @Immutable compose annotation.

expect annotation class Immutable()

In the Android side of the shared module add

actual typealias Immutable = androidx.compose.runtime.Immutable

In the iOS side add a dummy version.

actual annotation class Immutable

You can then annotate your data classes with @Immutable and they will properly be marked as stable by Compose.

  • Related