Search code examples
androidkotlinandroid-lifecyclekotlin-coroutines

Why does lifecycleScope.launch in a fragment block the UI thread?


This is blocking the UI thread, but if I use GlobalScope then the UI would't be blocked.

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()
            }
        }
    }

Solution

  • lifecycleScope.launch{} executes the code inside on the main thread by default. Try using the below code to launch the coroutine in the IO dispatcher (for long-running and intensive tasks).

    lifecycleScope.launch(Dispatchers.IO) {
           withContext(Dispatchers.Main) {
                Toast.makeText(activity, getString(R.string.txt_savinginprogress), Toast.LENGTH_SHORT).show()
           }
    }