带返回值的 Kotlin 协程 [英] Kotlin Coroutines with returning value

查看:76
本文介绍了带返回值的 Kotlin 协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个有返回值的协程方法.

例如)

fun funA() = async(CommonPool) {返回 1}fun funB() = async(CommonPool) {返回 2}有趣的总和(){发射 {val 总计 = funA().await() + funB().await()}}

如果我想在sum方法中返回total,我该怎么做?

喜欢

fun sum(): Int {发射 {val 总计 = funA().await() + funB().await()}总回报}

解决方案

要准确返回 Int,你需要跳出协程世界,这就是 runBlocking对于:

fun sum(): Int = runBlocking {funA().await() + funB().await()}

参见 在协程指南中桥接阻塞和非阻塞世界,以及组合挂起函数 了解如果您想使用 sum inside 协程,如何做到这一点.>

I want to create a coroutine method which has returning value.

For example)

fun funA() = async(CommonPool) {
    return 1
}

fun funB() = async(CommonPool) {
    return 2
}

fun sum() {
    launch {
        val total = funA().await() + funB().await()
    }
}

If I want to return total in sum method, how should I do?

like,

fun sum(): Int {
    launch {
        val total = funA().await() + funB().await()
    }   

    return total
}

解决方案

To return exactly Int, you need to get out of the coroutine world and that's what runBlocking is for:

fun sum(): Int = runBlocking {
    funA().await() + funB().await()
}

See Bridging blocking and non-blocking worlds in the coroutine guide, and Composing suspending functions for how to do it if you want to use sum inside coroutines.

这篇关于带返回值的 Kotlin 协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆