简体   繁体   English

使主线程等待协程 kotlin

[英]Make Main Thread to Wait for coroutine kotlin

I am trying to compress an image in android but and I don't want to use runBlocking .我正在尝试压缩 android 中的图像,但我不想使用runBlocking How can I make the main UI thread to wait for the compression to take place?如何让主 UI 线程等待压缩发生? Currently, I am doing this目前,我正在这样做

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

How to do it without runBlocking ?没有runBlocking怎么办?

You should not make the main-thread to wait for task completion.您不应该让主线程等待任务完成。 It causes freezing of your app until the main-thread gets free.它会导致您的应用程序冻结,直到主线程空闲。 You can do your long-running job in another thread, then switch to the main-thread to do whatever you want.您可以在另一个线程中完成长时间运行的工作,然后切换到主线程来做任何您想做的事情。

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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM