How to enable coroutine debug mode when running an Android App from Android Studio?

Viewed 891

I'm getting a coroutine exception while running my Android app in debug mode through Android Studio.

kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled

From the coroutines debugging documentation, I gather that I might get fuller stack trace information by enabling debug mode of coroutines.

It can be enabled either by setting system property DEBUG_PROPERTY_NAME or by running Java with enabled assertions (-ea flag).

This is where I'm stuck. What is the idiomatic way of achieving this in Android Studio? My project is configured using Gradle, and I am running on Windows. Ideally, there is a way to configure this through Gradle configuration so that coroutines debug mode is enabled for anyone pulling in this project through source control.

1 Answers

I haven't found a way to configure this through Android studio or Gradle. Information on doing so would still be useful to me. But, the following is verified to work; I got a full stack trace.

The "system property" refers to Java System Properties. They can be set at runtime using System.setProperty.

I therefore added the following code to the start of my Application.onCreate().

override fun onCreate() {
    // Enable coroutines debug mode in debug builds.
    if (BuildConfig.DEBUG) {
        System.setProperty(
            kotlinx.coroutines.DEBUG_PROPERTY_NAME,
            kotlinx.coroutines.DEBUG_PROPERTY_VALUE_ON
        )
    }

    ...

}
Related