[英]How Can I Make a Function That Returns a Value From a Coroutine?
我想寫一個 function 總是在 UI/主線程上調用。 在該 function 中,它將在后台線程上獲取文本(需要從設備上的文件中訪問某些內容),然后將該文本返回到主線程。 這可以以慣用的方式使用協程來完成嗎?
這是我到目前為止所做的,但我擔心它會在主線程上運行:
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 ?: ""
}
我想在 Android 活動中使用這個 function:
@Override
fun onCreate() {
// Other logic
nameTextView.text = MyHelperClass.getDisplayableName(this)
}
我正在尋找與使用回調處理異步線程類似的行為,但顯然沒有回調部分。
為了便於討論,假設我不能使用 LiveData 或 ViewModels。
您需要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()
}
}
}
您可以從onCreate
中這樣稱呼它
lifecycleScope.launch {
val name = getDisplayableName(this)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.