Search code examples
androidkotlinkotlin-coroutines

Variable not updated in a Coroutine


I made a coroutine to update the value of a variable, but it doesn't work:

fun findNameById(id: Long): String {
    var name = ""
    viewModelScope.launch(Dispatchers.IO) {
        val result = async { repository.findName(id) }.await()
        name = result
    }
    return name
}

The variable name is never updated, it is always an empty string and I don't understand why. The function findName works well, I checked it, but the variable name is never updated. Why?


Solution

  • When launching a new coroutine the remaining code immediately continues and the new coroutine is executed asynchronously.

    This is what happens here:

    1. name is set to "".
    2. A new coroutine is launched and the local variable name is captured for the lambda of launch.
    3. name is returned (which is "")
    4. The new coroutine is moved from the main thread to a separate thread of the IO dispatcher and then its block is executed.
    5. Even when findNameById is already finished the variable name is still around (because it was captured by 2.). This variable is now set to the value of result.
    6. The coroutine finishes and name is released and removed from memory because it isn't used any more, with the new value vanishing without being read even once.

    You can use async instead of launch if you need the result of a coroutine. You could also update some other variable instead (like a class property) that will be around even after findNameById finishes.