Search code examples
androidandroid-studioandroid-asynctaskandroid-lifecyclekotlin-coroutines

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

  • 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
        }
    }