我在函数中有一个返回值的后台任务。我用Kotlin协同程序。 我可以这样做:
fun backTask(): Int {
// Might take a few seconds
return 10
}
GlobalScope.launch(Dispatcher.Main){
val num = withContext(Dispatcher.IO) { backTask() }
toast("Number: $num")
}
所以它有效。究竟是什么让我定义我的后台任务函数,suspend function
如果从那里调用另一个suspend
函数,则应使用suspend
修饰符定义函数。例如,考虑以下情况:
suspend fun backTask(): Int = withContext(Dispatchers.IO) {
// Might take a few seconds, runs in background thread.
10
}
在这里,我们调用suspend fun withContext()
并将suspend
修饰符添加到backTask
函数中。如果我们不这样做,编译器将给出错误挂起函数withContext
应仅从协程或其他挂起函数调用。在使用协程的情况下,我们可以在不阻塞主线程的情况下调用backTask
函数:
GlobalScope.launch(Dispatcher.Main) {
val num = backTask() // not blocking the Main Thread
toast("Number: $num")
}
注意:GlobalScope.launch
is not recommended to use。
如果你尝试在其他任何地方使用该挂起函数,它会强制你使用协程。这意味着主线程没有意外阻塞:) -