Kotlin 24. Use of Dispatchers in Kotlin coroutine

Let's learn Kotlin together: concept: 22. The use of Dispatchers in Kotlin coroutine

  • Dispatchers.Main, for the Android main thread. It is used to call the suspend function, operate the UI framework, and update the LiveData object. When launch does not add parameters, its default value is Dispatchers.Main.
  • Dispatchers.IO: non-main thread. Used for disk operations (eg, Room operations), and network I/O requests (eg, calling server APIs).
  • Dispatchers.Default: Non-main thread, used for CPU-intensive operations, that is, it takes time to process. For example, list sorting, JSON parsing, image processing calculations, etc.

Here is an example of reading a URL image:

class MainActivity : AppCompatActivity() {
    
    

    private val IMAGE_URL = "https://i.kinja-img.com/gawker-media/image/upload/t_original/lj7y7c52vl96rjs4qjvx.jpg"
    private val coroutineScope = CoroutineScope(Dispatchers.Main)
    // Dispatchers.Main:Android 主线程。用于调用 suspend 函数,UI 框架操作,及更新 LiveData 对象。
    // coroutine 将运行在主线程,而不是 I/O 专用的线程中。
    // launch 在不加参数时,其默认值是 Dispatchers.Main。

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        coroutineScope.launch {
    
    
            // 这里我们先读取原图像
            val imageLoad = coroutineScope.async(Dispatchers.IO) {
    
     getOriginalBitmap() }
            // Dispatchers.IO:非主线程。用于磁盘操作(例如,Room 操作),及网络 I/O 请求(例如,调用服务器 API)。
            // Here we call the function getOriginalBitmap on the IO dispatcher.
            val originalBitmap: Bitmap = imageLoad.await()

            // 然后我们使用简单的图像处理将输入图像进行灰度。
            val processedImageLoad = coroutineScope.async(Dispatchers.Default) {
    
     imageProcess(originalBitmap) }
            // Dispatchers.Default 主要用于 CPU 密集型操作,就是说,需要花时间processing的。例如,list 排序,及 JSON 解析,图像处理计算等。
            val filteredBitmap: Bitmap = processedImageLoad.await()

            // wait for the bitmap
            loadImage(filteredBitmap)
        }
    }

    private fun getOriginalBitmap() =
        URL (IMAGE_URL).openStream().use {
    
    
            BitmapFactory.decodeStream(it)      // decode the stream into bitmap
        }

    private fun loadImage(bmp: Bitmap) {
    
    
        progressBar.visibility = View.GONE
        imageView.setImageBitmap(bmp)
        imageView.visibility = View.VISIBLE
    }

    private fun imageProcess(inputBitmap: Bitmap) = Filter.apply(inputBitmap)

}

Guess you like

Origin blog.csdn.net/zyctimes/article/details/128976732