Is there a way to return value from a coroutine scope? for example like this:

suspend fun signUpUser(signUpData : SignUpUserRequest) : User {

CoroutineScope(Dispatchers.IO).launch() {

        val response = retrofitInstance.socialSignUP(signUpData)
        if (response.success) {
            obj = response.data
        } else {
                obj = response.message
        }
    }.invokeOnCompletion {
        obj = response.message
    }

    return obj
}

问题是,只要调用了signupUser函数,就立即返回obj suspend语句,而不是使用响应值..它不是按顺序运行的,我期望的是第一个响应出现,然后函数返回obj,但它没有发生.为什么?

I tried run blocking, it served the purpose but is there better approach to do same task without run blocking? or is it alright?

Thanks in advance!

推荐答案

If you need to run works in parallel then you can use coroutineScope or async coroutine builder functions. However, in your case you don't have more than a request and so it could be sequantial. As mentioned in previous answer you can use withContext. Here is the small explaination from docs:

Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.

suspend fun getUser(signUpData: SignUpUserRequest): User = withContext(Dispatchers.IO) {
    // do your network request logic here and return the result
}

Please note that, when you are working with expression body with functions, always try to annotate return type explicitly.

EDIT

协同路由使用常规的Kotlin语法来处理异常:try/catch或内置的助手函数,如runCatching(内部使用try/catch).

Kotlin相关问答推荐

如何使用收件箱文件中的类运行Kotlin应用程序

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

为什么onEach不是挂起函数,而Collect是?

如何在Android应用判断上运行多个查询

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

使用 kotlin 流删除 map 中具有某些相似性的值

Kotlin 可空泛型

顶级属性的初始化

T except one class

内联函数导致单元测试代码覆盖率报告出错

如何创建 Kotlin DSL - DSL 语法 Kotlin

Kotlin boxed Int 不一样

如何在 kotlin 的片段类中更改 ActionBar 标题?

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

哪里可以找到aapt2日志(log)?

面临一些未知问题一些后端jvm内部错误

封闭 lambda 的隐式参数被shadowed

以Kotlin为单位的货币数据类型

如何在kotlin用mockito模仿lambda

Kotlin:获取文件的扩展名,例如.txt