'How do I return function value in lifecycle-aware coroutine scope in Android?

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 1:[1]

If returnValue() cannot be suspended function, there are basically only two options:

  1. 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
}
  1. Block the thread until the value is available:
fun returnValue(): Int {
    return runBlocking(viewModelScope.coroutineContext) {
        return@runBlocking 1
    }
}

Solution 2:[2]

you can try this

suspend fun returnValue(): Int {
    suspendCoroutine<Int> { cont ->
        viewModelScope.launch {
            cont.resume(1)
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kiskae
Solution 2 Yrii Borodkin