Steven Jeuris
Steven Jeuris

Reputation: 19100

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

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.

Upvotes: 8

Views: 3176

Answers (2)

donturner
donturner

Reputation: 19146

Coroutine debugging is not (currently) supported in Android Studio.

It was briefly added in 2021 but then removed due to performance problems. Here's the tracking bug.

There's also some additional information from the kotlinx-coroutines-debug project:

Android runtime does not support Instrument API necessary for kotlinx-coroutines-debug to function, triggering java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;, and it is not possible to use coroutine debugger along with Android emulator.

Source: https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-debug#debug-agent-and-android

Upvotes: 2

Steven Jeuris
Steven Jeuris

Reputation: 19100

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
        )
    }

    ...

}

Upvotes: 5

Related Questions