Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何生成从协程返回值的函数?_Android_Kotlin Coroutines - Fatal编程技术网

Android 如何生成从协程返回值的函数?

Android 如何生成从协程返回值的函数?,android,kotlin-coroutines,Android,Kotlin Coroutines,我想编写一个总是在UI/主线程上调用的函数。在该函数中,它将获取后台线程上的文本,需要从设备上的文件访问某些内容,然后将该文本返回到主线程。这可以用一种惯用的方式使用协同程序来实现吗 以下是我迄今为止所做的工作,但我担心它将在主线上运行: fun getDisplayableNamecontext:上下文:字符串= ifsomeCondition context.getStringR.string.someString else运行阻塞{ 变量名称字符串:字符串?=null launchDisp

我想编写一个总是在UI/主线程上调用的函数。在该函数中,它将获取后台线程上的文本,需要从设备上的文件访问某些内容,然后将该文本返回到主线程。这可以用一种惯用的方式使用协同程序来实现吗

以下是我迄今为止所做的工作,但我担心它将在主线上运行:

fun getDisplayableNamecontext:上下文:字符串= ifsomeCondition context.getStringR.string.someString else运行阻塞{ 变量名称字符串:字符串?=null launchDispatchers.IO{ name=//某些后台逻辑,其中name可能仍然为null } 姓名 } 我想在Android活动中使用此功能:

@Override
fun onCreate() {
    // Other logic
    nameTextView.text = MyHelperClass.getDisplayableName(this)
}
我正在寻找与使用回调处理异步线程类似的行为,但显然没有回调部分

为了便于讨论,假设我不能使用LiveData或ViewModels。

您需要一个挂起函数

您可以从onCreate这样称呼它


将它与实时数据结合起来,这样您就可以在不包含回调的情况下观察更改让我们假设我不能使用LiveData或ViewModels。非常感谢您的输入。但是,如果我只是将作用域作为参数传递到函数中,为什么它不起作用呢?难道不能这样做吗?或者挂起修饰符是唯一的方法吗?在代码中,您使用的是runBlocking,它有效地阻止UI线程,直到操作完成。如果要使用协同路由在后台运行代码,则必须使用suspend函数。
suspend fun getDisplayableName(context: Context): String =
    if(someCondition) {
        context.getString(R.string.someString)
    } else {
        withContext(Dispatchers.IO) {
            val name = // some background logic, where name may still be null
            name.orEmpty()
        }
    }
}
lifecycleScope.launch {
    val name = getDisplayableName(this)
}