Adding "Debug" Checks To Your Compose Multiplatform Project: Android, iOS, and Desktop

Adding "Debug" Checks To Your Compose Multiplatform Project: Android, iOS, and Desktop

ยท

2 min read

While working on my recent Compose Multiplatform project, Sync Sphere, which targets iOS, Android, and Desktop, I needed to add some debug checks in my application to perform some different functionality when in debug mode.

When debugging (which I mean to be developing locally), I wanted to target a different table for my remote database, so I wasn't cluttering up production data with all of my local development data.

The solution wasn't super obvious to me when I originally set out to solve this problem, so I wanted to share what ended up working for me.

In my commonMain, I defined a BuildConfig interface and an expect declaration for my BuildConfigImpl

interface BuildConfig {
    fun isDebug(): Boolean
}

expect class BuildConfigImpl : BuildConfig

In my androidMain src set, it looks pretty familiar to an Android developer:

actual class BuildConfigImpl(private val applicationContext: Context) : BuildConfig {
    override fun isDebug(): Boolean {
        return 0 != applicationContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
    }
}

In my iosMain src set, it looks pretty familiar to an iOS developer. (I think at least, I'm not a good iOS developer ๐Ÿ˜…)

import kotlin.experimental.ExperimentalNativeApi

actual class BuildConfigImpl() : BuildConfig {

    @OptIn(ExperimentalNativeApi::class)
    override fun isDebug(): Boolean {
        return Platform.isDebugBinary
    }
}

In my Desktop target and src set, desktopMain , I use System Properties to define a local debug flag to pass along to my application so it can be flagged true when I'm working locally.

First, I added a new property to my local gradle.properties located in my Gradle home directory (~/.gradle/gradle.properties)

systemProp.syncSphereDebug=true

Then, in my desktopApp build file, I added the following code:

tasks.withType<JavaExec>().configureEach {
    systemProperty("syncSphereDebug", System.getProperty("syncSphereDebug"))
}

This allows me to now have an implementation for BuildConfigImpl for Desktop that looks like:

actual class BuildConfigImpl() : BuildConfig {
    override fun isDebug(): Boolean {
        val debugSystemProperty = System.getProperty("syncSphereDebug")
        return debugSystemProperty?.toBoolean() ?: false
    }
}

I hope this post was helpful where I covered enabling some sort of debug / local environment for providing different behavior when developing your Compose Multiplatform project!

ย