KirstenLy
KirstenLy

Reputation: 1226

Kotlin, Android, how to debug coroutines correctly?

I'm trying to debug my coroutines, and breakpoints placed into suspend function don't work. Pls help me understand why.

Working with Android Studio.

Ok, I launch a coroutine from viewModelScope:

    viewModelScope.launch(IO) {
        when(val result = interactor.getAllWords()){...}
    }

In getAllWords() I wrote:

    override suspend fun getAllWords(): WordResult {
        val words = mutableListOf<Word>()

        when (val wordsResult = getAllWordsWithoutFiltersApplying()) {}

        ...

        return getWordsWithSelectedPattern()

I have two suspend functions: getAllWordsWithoutFiltersApplying() and getWordsWithSelectedPattern(). I have a breakpoints into both of them, but they did't trigger in debug mode.

At the same time, line val words = mutableListOf<Word>() is triggering, when I put breakpoint to its line.

And, if I put some log stuff into "untracing" function, they will be work. I say it to make it clear, suspend function works. Breakpoints are not.

What should I do to debug them?

*Screenshot added. Look at the left side with row of icons. Why my lines are not available?

enter image description here

Upvotes: 41

Views: 18538

Answers (4)

nilsi
nilsi

Reputation: 10761

I had forgot minifyEnabled set to true in my build.gradle file

  buildTypes {
    release {
      minifyEnabled true
    }
    debug {
      minifyEnabled true <- Should be false for these breakpoints to work
    }
  }

Upvotes: 1

mohsen zandie
mohsen zandie

Reputation: 77

It still does not work for me because I run the app first then attach the debugger, but when I use debug instead, it works.

Upvotes: 5

Jeffery Ma
Jeffery Ma

Reputation: 3341

Based on your sample code, you switch the coroutine context between MAIN and IO so when you set the breakpoint, make sure the suspend option is ALL

To show the option of the breakpoint. Set a breakpoint with the left click of your mouse, and then right click your mouse on the breakpoint.

If you are using the JetBrain IDE, according to the document, when you set the breakpoint to make sure the suspend option is ALL not thread. it works for me.

enter image description here

and more detail you can check the document

enter image description here

Upvotes: 48

Arun P M
Arun P M

Reputation: 370

I know I'm late, but this is for those people who made similar mistakes like me. I've also faced this issue recently and the root cause was related to dependencies. Actually I added coroutine core dependency but I forget to add coroutine android dependency. Please make sure both dependencies are present in your gradle file as shown below.

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.4"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'

Upvotes: 1

Related Questions