方法声明 kotlin async{}
Method Declaration kotlin async{}
我想知道什么是长期 运行ning 任务的正确声明。
suspend fun methodName(image: Bitmap?): String? = async {
// heavy task
}.await()
或
fun methodName(image: Bitmap?): String? {
//heavyTask
}
并在代码中使用
async{
methodName()
}.await()
第一个限制繁重的操作总是在后台线程上执行。所以,它是安全的(在某种程度上它将 运行 在后台线程上,这样新的开发人员一定会在可挂起的构造中使用它)。
哪种方法更好?
考虑在您的情况下使用 withContext()
而不是 async{}.await()
。
关于你的问题,恕我直言,最好使用这样的构造:
suspend fun methodName(image: Bitmap?): String? = withContext(CommonPool) {
// heavy task
}
我相信 suspend
关键字是对用户的强烈警告,以防止在敏感线程中使用特定函数。但情况可能并非总是如此。正如 coroutines documentation 中所说:
the library can decide to proceed without suspension, if the result for the call in question is already available
如果"heavy task"是为了直截了当。 (例如:复制文件)我个人只是在不创建协程的情况下将挂起添加到函数中。用户完全负责调用此函数的位置。
@Throws(IOException::class)
suspend fun copy(input: File, output: File) {
//copying
}
如果"heavy task"由其他suspend
函数组成。警告一般是函数参数中的couroutineContext
。在内部它使用像 withContext()
这样的函数。
withContext : suspends until it completes, and returns the result
@Throws(IOException::class)
suspend fun copyMultiple(context: CoroutineContext, pairFiles: List<Pair<File, File>>) {
pairFiles.forEach { (input, output) ->
withContext(context) {
copy(input, output)
}
}
}
我想知道什么是长期 运行ning 任务的正确声明。
suspend fun methodName(image: Bitmap?): String? = async {
// heavy task
}.await()
或
fun methodName(image: Bitmap?): String? {
//heavyTask
}
并在代码中使用
async{
methodName()
}.await()
第一个限制繁重的操作总是在后台线程上执行。所以,它是安全的(在某种程度上它将 运行 在后台线程上,这样新的开发人员一定会在可挂起的构造中使用它)。
哪种方法更好?
考虑在您的情况下使用 withContext()
而不是 async{}.await()
。
关于你的问题,恕我直言,最好使用这样的构造:
suspend fun methodName(image: Bitmap?): String? = withContext(CommonPool) {
// heavy task
}
我相信 suspend
关键字是对用户的强烈警告,以防止在敏感线程中使用特定函数。但情况可能并非总是如此。正如 coroutines documentation 中所说:
the library can decide to proceed without suspension, if the result for the call in question is already available
如果"heavy task"是为了直截了当。 (例如:复制文件)我个人只是在不创建协程的情况下将挂起添加到函数中。用户完全负责调用此函数的位置。
@Throws(IOException::class)
suspend fun copy(input: File, output: File) {
//copying
}
如果"heavy task"由其他suspend
函数组成。警告一般是函数参数中的couroutineContext
。在内部它使用像 withContext()
这样的函数。
withContext : suspends until it completes, and returns the result
@Throws(IOException::class)
suspend fun copyMultiple(context: CoroutineContext, pairFiles: List<Pair<File, File>>) {
pairFiles.forEach { (input, output) ->
withContext(context) {
copy(input, output)
}
}
}