为什么我要将后台任务定义为挂起功能

问题描述 投票:0回答:2

我在函数中有一个返回值的后台任务。我用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

android kotlin kotlinx.coroutines
2个回答
1
投票

如果从那里调用另一个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


0
投票

如果你尝试在其他任何地方使用该挂起函数,它会强制你使用协程。这意味着主线程没有意外阻塞:) -

© www.soinside.com 2019 - 2024. All rights reserved.