android - 当我使用延迟时,我应该从主线程切换到默认线程还是 IO 线程
问题描述
有时我的片段范围需要等待才能执行一些视图内容。在这些情况下,我将延迟(ms)函数添加到我的范围中。但是我的作用域是用Dispathers.Main初始化的。我知道与Thread.sleep(ms)不同,delay(ms)不会阻塞当前线程。我应该考虑哪个线程执行延迟功能?
val scope = CoroutineScope(Dispatchers.Main)
scope.launch {
//do i really need to switch IO
withContext(Dispatchers.IO) {
delay(4000)
}
someUIStuff()
}
}
解决方案
无需切换,delay
是一个suspend
函数,它会暂停当前Coroutinescope
而不是正在执行的Thread
. 根据delay
功能文档,检查第一点
/**
* Delays coroutine for a given time without blocking a thread and resumes it after a specified time.
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
* immediately resumes with [CancellationException].
*
* Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
*
* Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context.
* @param timeMillis time in milliseconds.
*/
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
推荐阅读
- swift - 可选的委托方法不是可选的
- quill - QuillJS:自定义 attr alt
- node.js - 如何将 NodeJs 日志从控制台重定向到文件
- android - 在android中的click事件上执行耗时的任务
- jquery - Kendo UI Grid Multicheck 按 Id 过滤
- html - 如何使div中的背景图像响应
- hadoop - Hadoop集群处于安全模式(Namenode处于安全模式)我需要释放哪些资源才能删除安全模式?
- c# - Visual Studio 2017 中没有启动对象
- cordova - 将 StartApp 广告集成到 Ionic 应用程序中
- ruby-on-rails - 在 rspec after(:suite) 中访问测试结果