In the code snippet below, how to get the value of isValid after viewModelScope.launch is finished.
viewModelScope.launch runs at last, inside fun checkCode(). So fun checkCode() is always return false.
fun someListener() {
if (checkCode() == true) {
//do something
}
}
fun checkCode(): Boolean {
var isValid = false
viewModelScope.launch(Dispatchers.Main) {
val response = withContext(Dispatchers.IO) {
// something do in background
}
if (response == "someString") {
isValid = true
// tried to type "return isValid" but syntax error
}
}
// the problem is below statements run before viewModelScope.launch
if (isValid) return true
else return false
}