使主线程等待协程科特林

时间:2020-08-19 10:53:31

标签: android kotlin

我正在尝试在android中压缩图像,但是我不想使用runBlocking。 如何使主UI线程等待压缩发生? 目前,我正在这样做

var compressedImage: File? = null
runBlocking {
    compressedImage = Compressor.compress(this@UpdateProfileActivity, cachedFile.absoluteFile)
}
camera = "gallery"
//doing something with the compressedImage.

在没有runBlocking的情况下如何做?

1 个答案:

答案 0 :(得分:1)

您不应使主线程等待任务完成。这会导致您的应用程序冻结,直到主线程释放为止。您可以在另一个线程中执行长期运行的工作,然后切换到主线程以执行所需的任何操作。

var compressedImage: File? = null
CoroutineScope().launch(Dispatchers.IO) {
    compressedImage = Compressor.compress(this@UpdateProfileActivity, cachedFile.absoluteFile)
    
    withContext(Dispatchers.Main) {
        camera = "gallery"
        // doing something with the compressedImage.
    }
}