Issue
fun returnValue(): Int {
viewModelScope.launch {
return 1 // Something like this
}
}
I want to return some value in a viewModelScope like the above. I don't want my function to be suspended function. How do I achieve that?
Solution
If returnValue()
cannot be suspended function, there are basically only two options:
- Turn the return type into
Deferred<Int>
and make the caller responsible for handling the return value at a later point. The body becomes:
fun returnValue(): Deferred<Int> = viewModelScope.async {
return@async 1
}
- Block the thread until the value is available:
fun returnValue(): Int {
return runBlocking(viewModelScope.coroutineContext) {
return@runBlocking 1
}
}
Answered By - Kiskae
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.