为什么片段中的 lifecycleScope.launch 会阻塞 UI 线程?
Why does lifecycleScope.launch in a fragment block the UI thread?
这会阻塞 UI 线程,但是如果我使用 GlobalScope 那么 UI 就不会被阻塞。
lifecycleScope.launch {
activity?.runOnUiThread {
Toast.makeText(activity, getString(R.string.txt_savinginprogress), Toast.LENGTH_SHORT).show()
}
val fileName = "Picture" + System.currentTimeMillis().toString()
val folderName = "BucketList"
val bitmap: Bitmap? = photoURI?.let { it1 -> getBitmapFromUri(it1) }
activity?.let {
bitmap?.let { it1 ->
PhotoSaveHelper(it).savePhoto(fileName, folderName, it1)
}
}
activity?.runOnUiThread {
Toast.makeText(activity, getString(R.string.txt_saved), Toast.LENGTH_SHORT).show()
}
}
}
lifecycleScope.launch{}
默认在main
线程上执行里面的代码。
尝试使用以下代码在 IO 调度程序中启动协程(对于长运行 和密集任务)。
lifecycleScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
Toast.makeText(activity, getString(R.string.txt_savinginprogress), Toast.LENGTH_SHORT).show()
}
}
这会阻塞 UI 线程,但是如果我使用 GlobalScope 那么 UI 就不会被阻塞。
lifecycleScope.launch {
activity?.runOnUiThread {
Toast.makeText(activity, getString(R.string.txt_savinginprogress), Toast.LENGTH_SHORT).show()
}
val fileName = "Picture" + System.currentTimeMillis().toString()
val folderName = "BucketList"
val bitmap: Bitmap? = photoURI?.let { it1 -> getBitmapFromUri(it1) }
activity?.let {
bitmap?.let { it1 ->
PhotoSaveHelper(it).savePhoto(fileName, folderName, it1)
}
}
activity?.runOnUiThread {
Toast.makeText(activity, getString(R.string.txt_saved), Toast.LENGTH_SHORT).show()
}
}
}
lifecycleScope.launch{}
默认在main
线程上执行里面的代码。
尝试使用以下代码在 IO 调度程序中启动协程(对于长运行 和密集任务)。
lifecycleScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
Toast.makeText(activity, getString(R.string.txt_savinginprogress), Toast.LENGTH_SHORT).show()
}
}