首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从CoroutineScope返回函数

从CoroutineScope返回函数
EN

Stack Overflow用户
提问于 2021-02-21 03:28:10
回答 3查看 49关注 0票数 0

我的代码类似于下面的代码。

代码语言:javascript
复制
suspend fun foo() {
    withContext(Dispatchers.IO) {
        // how to return at foo?
    }
    // more code here
}

如何在foo退货?当我只做普通的老式return时,我得到了'return' is not allowed herereturn@withContext的建议,但我不想调用withContext上的return,我想调用foo上的return。

EN

回答 3

Stack Overflow用户

发布于 2021-02-21 04:02:39

代码语言:javascript
复制
suspend fun foo() {
   return withContext(Dispatchers.IO) {
        return@withContext something
    }
}
票数 0
EN

Stack Overflow用户

发布于 2021-02-21 04:40:27

您不能从withContext内部调用return@foo,所以您唯一的选择是从withContext返回一些值,然后检查它,然后决定是继续还是返回。

例如:

代码语言:javascript
复制
suspend fun foo() {
    withContext(Dispatchers.IO) {
        // Code that might return null or not
    }?.let {
        // More code here
    }
}
票数 0
EN

Stack Overflow用户

发布于 2021-02-21 11:45:11

我猜您想要做的是,根据withContext代码块中的某个分支代码,有条件地提前从foo()返回。

因为withContext不是内联函数,所以它只能从自身返回。所以你可以这样做:

代码语言:javascript
复制
suspend fun foo() {
    var shouldContinue = true
    withContext(Dispatchers.IO) {
        //some code
        if (something) { // condition under which you want to return early
            shouldContinue = false
            return@withContext
        }
        // some more code
    }
    if (!shouldContinue) {
        return
    }
    // more code here
}

或者让您的withContext从它的所有分支返回一个布尔值,以确定是否继续:

代码语言:javascript
复制
suspend fun foo() {
    val shouldContinue = withContext(Dispatchers.IO) {
        //some code
        if (something) { // condition under which you want to return early
            return@withContext false
        }
        // some more code
        true // implicit return
    }
    if (!shouldContinue) {
        return
    }
    // more code here
}

或者,如果你使用它来产生一些你要做的事情的结果,那么对于它可以提前退出而不返回任何东西的情况,你可以返回null:

代码语言:javascript
复制
suspend fun foo() {
    val result = withContext(Dispatchers.IO) {
        //some code
        if (something) { // condition under which you want to return early
            return@withContext null
        }
        // some more code
        yourResult
    }
    result ?: return // no result, return early
    // do something with non-null result
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66295703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档