gpt4 book ai didi

android - 方法声明 kotlin async{}

转载 作者:太空狗 更新时间:2023-10-29 13:04:01 25 4
gpt4 key购买 nike

我想知道长时间运行的任务的正确声明是什么。

suspend fun methodName(image: Bitmap?): String? = async {
// heavy task
}.await()

fun methodName(image: Bitmap?): String? {
//heavyTask
}

并在代码中使用

async{
methodName()
}.await()

第一个限制繁重的操作总是在后台线程上执行。所以,它是安全的(在某种程度上它将在后台线程上运行,因此新的开发人员一定会在可挂起的构造中使用它)。

哪种方法更好?

最佳答案

我相信 suspend 关键字是对用户的强烈警告,以防止在敏感线程中使用特定函数。但情况可能并非总是如此。如 coroutines documentation 中所述:

the library can decide to proceed without suspension, if the result for the call in question is already available

如果说“任务重”,直截了当。 (例如:复制文件)我个人只是在不创建协程的情况下将挂起添加到函数中。用户全权负责调用此函数的位置。

@Throws(IOException::class)
suspend fun copy(input: File, output: File) {
//copying
}

如果“繁重的任务”由其他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)
}
}
}

关于android - 方法声明 kotlin async{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50926125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com