美文网首页
Android Kotlin之withContext(协程)使用

Android Kotlin之withContext(协程)使用

作者: Lee_5566 | 来源:发表于2021-01-14 20:42 被阅读0次
image.png

withContext

kotlin 中 GlobalScope 类提供了几个创建协程的构造函数:

  • launch: 创建协程
  • async : 创建带返回值的协程,返回的是 Deferred 类
  • withContext:不创建新的协程,指定协程上运行代码块
  • runBlocking:不是 GlobalScope 的 API,可以独立使用,区别是 runBlocking 里面的 delay 会阻塞线程,而 launch 创建的不会

withContextt这个函数主要可以切换到指定的线程,并在闭包内的逻辑执行结束之后,自动把线程切回去继续执行:

coroutineScope.launch(Dispatchers.Main) {      //  在 UI 线程开始
    val image = withContext(Dispatchers.IO) {  // 切换到 IO 线程,并在执行完成后切回 UI 线程
        getImage(imageId)                      // 将会运行在 IO 线程
    }
    avatarIv.setImageBitmap(image)             // 回到 UI 线程更新 UI
} 

相关文章

网友评论

      本文标题:Android Kotlin之withContext(协程)使用

      本文链接:https://www.haomeiwen.com/subject/ekzkaktx.html