Kotlin协程之Dispather

这篇博客将会介绍几种 Dispatchers 的用法。

Dispatchers 可以决定协程运行在什么线程上,协程将在特定的线程中运行这些任务。

协程中的Dispatchers 与 RxJava 中的 Schedulers 类似

我们在安卓项目中通常使用以下几种 Dispathers

但是当我们查看文档,还会发现还有一种

  • Dispathers.UnConfined

所以,在 kotlin 协程中有四种类型的 Dispathers

  • Dispatchers.Default
  • Dispatchers.IO
  • Dispathers.Main
  • Dispathers.UnConfined

Dispathers.Default

我们应该使用Dispathers.Default去执行 CPU 密集型任务。

举例如下:

  • 执行计算繁琐的任务,例如矩阵聚酸
  • 对内存中存在的较大列表执行任何操作,例如排序、过滤、查找等
  • 对内存中的 bitmap 进行过滤操作。注意,不是指硬盘中读取图片文件
  • 解析内存中可用的 JSON。注意,不是指从文件中读取 JSON 文件
  • 缩放内存中已经存在的 bitmap。
  • 对内存中的 bitmap 任意操作。

现在我们知道了什么时候该使用Dispathers.Default

我们可以认为 Dispather.Default 与 RxJava 中的 Schedulers.computation()

kotlin 复制代码
launch(Dispathers.Default) {
	// cpu 密集任务
}

Dispathers.IO

我们应该使用Dispathers.IO 去处理硬盘或者网络 IO 任务。

举例如下:

  • 任何网络相关的操作,如网络请求
  • 从服务端下载文件
  • 将文件从一个地方移动到另一个地方
  • 读取文件
  • 写入文件
  • 数据库查询
  • 加载 sp

简而言之,任何文件系统操作或者网络相关操作都应该使用Dispathers.IO,因为这是IO 相关的任务。

我们可以认为 Dispathers.IO与Rxjava 中的 Schedulers.io()类似

Dispathers.Main

我们应该使用Dispatchers.Main去执行一个在安卓主线程运行的协程。我们都知道应该在什么情况下使用主线程。通常都是在执行 UI 操作或者一些简单的任务。

举例如下:

  • 处理 UI 相关任务
  • 简单任务,如内存中较小长度列表的排序。

我们可以认为Dispatcher.Main与 RxAndroid 中的AndroidSchedulers.mainThread()类型

kotlin 复制代码
launch(Dispathers.Main) {
    // 主线程相关任务
}

Dispathers.Unconfined

As per the official documentation: A coroutine dispatcher that is not confined to any specific thread. It executes the initial continuation of a coroutine in the current call frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy.

它将不改变线程。当其启动的时候,它运行在启动它的线程之上,当其被恢复的时候,它运行在恢复它的线程智商。

简而言之: 当我们不关心协程运行在什么线程之上的时候,就可以使用Dispathers.Unconfined

kotlin 复制代码
launch(Dispathers.Unconfined) {
    // 不关心运行在何种线程之上的任务
}
相关推荐
雾屿_Mistisle5 分钟前
文件包含漏洞(File Inclusion)
android
sycmancia9 分钟前
Qt——复习篇painter
开发语言·qt
赵钰老师11 分钟前
R语言数据统计分析与ggplot2高级绘图
开发语言·数据分析·r语言
刘名喜24 分钟前
第21篇-N+1问题与fetch-join-EntityGraph
kotlin·springboot
多弗朗皮卡丘38 分钟前
C语言梦开始的地方3
c语言·开发语言
Bonnie_12151 小时前
08-JUC并发基础-AQS-补充共享锁
java·开发语言
qq_401700411 小时前
Qt 程序启动太乱?重新设计你的 Application 生命周期
开发语言·qt
小孔龙1 小时前
Android 图形系统全景
android·计算机图形学
2501_915921431 小时前
详细解析,iOS 应用上架 App Store 的完整流程与指南
android·ios·小程序·https·uni-app·iphone·webview
qq_425516181 小时前
录音转文字工具免费下载:免费额度与功能限制对比
android·人工智能·智能手机·powerpoint