[英]How Can I Make a Function That Returns a Value From a Coroutine?
I want to write a function that will always be called on the UI/main thread.我想写一个 function 总是在 UI/主线程上调用。 Within that function, it will fetch text on a background thread (needs to access something from a file on the device) and then return that text to the main thread.在该 function 中,它将在后台线程上获取文本(需要从设备上的文件中访问某些内容),然后将该文本返回到主线程。 Can this be done using coroutines in an idiomatic way?这可以以惯用的方式使用协程来完成吗?
Here is what I have done so far, but I fear it will run on the main thread:这是我到目前为止所做的,但我担心它会在主线程上运行:
fun getDisplayableName(context: Context): String =
if(someCondition)
context.getString(R.string.someString)
else runBlocking{
var name String: String? = null
launch(Dispatchers.IO) {
name = // some background logic, where name may still be null
}
name ?: ""
}
I want to use this function in an Android activity:我想在 Android 活动中使用这个 function:
@Override
fun onCreate() {
// Other logic
nameTextView.text = MyHelperClass.getDisplayableName(this)
}
I'm looking for similar behavior to handling asynchronous threading with callbacks, but obviously without the callbacks part.我正在寻找与使用回调处理异步线程类似的行为,但显然没有回调部分。
For the sake of discussion, assume I can't use LiveData or ViewModels.为了便于讨论,假设我不能使用 LiveData 或 ViewModels。
You need a suspend
function您需要suspend
function
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()
}
}
}
You would call it like this from onCreate
您可以从onCreate
中这样称呼它
lifecycleScope.launch {
val name = getDisplayableName(this)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.