简体   繁体   English

如何在 Android 的生命周期感知协程范围内返回函数值?

[英]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.我想在上面的 viewModelScope 中返回一些值。 I don't want my function to be suspended function.我不希望我的功能被挂起。 How do I achieve that?我该如何做到这一点?

If returnValue() cannot be suspended function, there are basically only two options:如果returnValue()不能挂起函数,基本上只有两种选择:

  1. Turn the return type into Deferred<Int> and make the caller responsible for handling the return value at a later point.将返回类型转换为Deferred<Int>并让调用者负责稍后处理返回值。 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
    }
}

you can try this你可以试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android 生命周期感知组件如何检测 ViewModel 中的配置更改 - Android How Lifecycle-Aware Components Detect Configuration Change inside ViewModel 如何在协程范围内返回值? - How to return value in coroutine scope? Android Jetpack:使用 LiveData 和 ViewModel 执行生命周期感知的周期性任务 - Android Jetpack: lifecycle-aware recurrent periodic task execution with LiveData and ViewModels 如何从协程 scope 返回值 - How to return value from coroutine scope 如何将 ViewModelScope 等异步协程 scope 的值返回到您的 UI? - How to return value from async coroutine scope such as ViewModelScope to your UI? 协程生命周期范围和 isActive 不起作用? - Coroutine Lifecycle Scope and isActive not working? 如何在 Android 上停止 Kotlin 协程? - How do I stop a Kotlin coroutine on Android? 如何使用Proguard调用可识别Android生命周期的组件? - How to make Android lifecycle aware component get called on using Proguard? 如何制作从协程返回值的 Function? - How Can I Make a Function That Returns a Value From a Coroutine? android的生命周期回调是否被视为“协程”? - Is android's lifecycle callback's considered a “coroutine”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM