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?
When launching a new coroutine the remaining code immediately continues and the new coroutine is executed asynchronously.
This is what happens here:
name
is set to ""
.name
is captured for the lambda of launch
.name
is returned (which is ""
)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
.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.