Search code examples
androidkotlinandroid-studiodebuggingbreakpoints

How to prevent variables from being optimized out when setting kotlin breakpoints in Android Studio


I'm trying to check the value of variables while at a breakpoint but Android Studio says my variable "states has been optimised out"[sic].

    val states = mutableListOf<UiState>()
    backgroundScope.launch(Dispatchers.Unconfined) {
        viewModel.uiState.toList(states)
    }
    assertEquals(true, states[0].isLoading)

    // Breakpoint here
    viewModel.fooBarBaz()

I know I can set a breakpoint higher up or add a line of code - like a print statement - below the breakpoint which uses the variable, but that's just annoying. How do I tell Android Studio to not optimize out my local variables?


Solution

  • Use kotlinOptions and freeCompilerArgs = listOf("-Xdebug") inside build.gradle.kts.

    android {
        ...
        buildTypes {
            getByName("debug") {
                isMinifyEnabled = false
    
                kotlinOptions {
                    freeCompilerArgs = listOf("-Xdebug")
                }
            }
            getByName("release") {
                ...
            }
        }
    ...
    }