Kotlin 正确使用协程调度程序Main和Default
我正在尝试做一个杯重计算,然后想更新用户界面 下面是我的代码:Kotlin 正确使用协程调度程序Main和Default,kotlin,kotlin-coroutines,coroutine,Kotlin,Kotlin Coroutines,Coroutine,我正在尝试做一个杯重计算,然后想更新用户界面 下面是我的代码: private fun updateData() { GlobalScope.launch(Dispatchers.Default){ //work on default thread while (true){ response.forEach { val out = doIntensiveWork()
private fun updateData() {
GlobalScope.launch(Dispatchers.Default){ //work on default thread
while (true){
response.forEach {
val out = doIntensiveWork()
withContext(Dispatchers.Main){ //update on main thread
_data.postValue(out)
delay(1500L)
}
}
}
}
}
这种使用协同程序的方式可以吗?由于运行整个主控台上的工作也没有明显的效果和工作精细
private fun updateData() {
GlobalScope.launch(Dispatchers.Main){ //work on Main thread
while (true){
response.forEach {
val out = doIntensiveWork()
_data.postValue(out)
delay(1500L)
}
}
}
}
建议使用哪一种?您应该避免使用
GlobalScope
,原因如下:
你应该考虑从进行大量计算。
suspen fun doheavystuf():Result=withContext(Dispatchers.IO){//或Dispatchers.Default
// ...
}
suspend fun waitForHeavyStuf()=withContext(Dispatchers.Main){
val result=doHeavyStuff()//在IO线程上运行,但结果在主线程上返回
updateYourUI()
}
文档
- 我推荐Kotlin合作项目
- 主:ui线程,用于与ui相关的快速操作
- IO:后台线程,用于网络/文件系统/数据库的数据事务
- 默认值:后台线程,用于解析JSON或重建列表等其他繁重操作
- 帮助视频:
- 有益阅读: