Android 生命周期示波器中的Kotlin协同程序不';t形块主螺纹
我对ViewModels中的协程感到困惑 我的问题很简单:为什么以下协同程序似乎没有阻止UIThread?(协同程序运行时,UI仍然平滑) 我的片段就在这里:Android 生命周期示波器中的Kotlin协同程序不';t形块主螺纹,android,kotlin,mvvm,coroutine,Android,Kotlin,Mvvm,Coroutine,我对ViewModels中的协程感到困惑 我的问题很简单:为什么以下协同程序似乎没有阻止UIThread?(协同程序运行时,UI仍然平滑) 我的片段就在这里: class FragmentSeePaths : Fragment(R.layout.fragment_see_paths), PathRecyclerAdapter.OnSetPathForWidgetListener { private val pathViewModel: PathViewModel by a
class FragmentSeePaths : Fragment(R.layout.fragment_see_paths),
PathRecyclerAdapter.OnSetPathForWidgetListener {
private val pathViewModel: PathViewModel by activityViewModels()
private lateinit var binding: FragmentSeePathsBinding
private lateinit var listener: OnAddLineRequestListener
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
}
private fun observeWidgetPath() {
pathViewModel.getUserWidgetPath().observe(viewLifecycleOwner, Observer {
if (it != null) {
lifecycleScope.launch {
val times = pathViewModel.fetchBusTime(it)
updateUI(it, times)
}
}
})
}
下面是使用FetchBusticTime方法拍摄的视图模型:
suspend fun fetchBusTime(path: Path): Pair<List<Time>?, List<Time>?> {
Log.v("fetchBusTimeUI", Thread.currentThread().name) // Main
// Some network requests made with Retrofit
val timesResponseStartPoint: GinkoTimesResponse? = repository.getTimes(
path.startingPoint.startName,
path.line.lineId,
path.isStartPointNaturalWay
)
val timesResponseEndPoint: GinkoTimesResponse? = repository.getTimes(
path.endingPoint.endName,
path.line.lineId,
path.isStartPointNaturalWay
)
return timesResponseStartPoint to timesResponseEndPoint
}
suspend-me(路径:path):成对{
Log.v(“fetchbastimeui”,Thread.currentThread().name)//Main
//通过改造提出的一些网络请求
val timesResponseStartPoint:GinkoTimesResponse?=repository.getTimes(
path.startingPoint.startName,
path.line.lineId,
path.isStartPointNaturalWay
)
val timesResponseEndPoint:GinkoTimesResponse?=repository.getTimes(
path.endingPoint.endName,
path.line.lineId,
path.isStartPointNaturalWay
)
返回TimeResponseStartPoint到TimeResponseEndPoint
}
启动
允许我们在后台启动协同程序,同时继续工作<代码>挂起函数可以挂起当前协同程序的执行,而不阻塞当前线程。我们可以在以下任何一个调度员的指导下启动协同程序
fun main() {
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main thread continues here immediately
runBlocking { // but this expression blocks the main thread
delay(2000L) // ... while we delay for 2 seconds to keep JVM alive
}
}
这些评论应该不言自明。这将立即打印“Hello”,并在一秒钟后添加“World!”。
这与您的代码相同,挂起函数fetchburstime()
将在不阻塞线程的情况下执行,并且在此方法内完成操作后,它将执行updateUI(it,times)
有关这方面的更多详细信息,请阅读本文您是否阅读了关于什么是协同程序的文档?挂起函数从不阻塞主线程(只要它们被正确写入)。他们会暂停执行协同程序(在主线程的情况下,它会释放它去做它需要为UI做的任何其他事情),直到它们返回为止。是的,我读过。问题是,将协同路由放在Dispatcher.IO或Dispatcher.default中有什么意义?我想这段视频让我意识到我的代码中发生了什么。在主线程中启动协同程序时,当调用Refrinform时,Refrinform会自动切换上下文。有意义吗?只要运行阻塞代码,正确编写的任何挂起函数都将从主调度器切换。简单挂起函数的常用用法是
suspendfunx(param:Int)=withContext(Dispatchers.IO){/*someblockingcode*/}
。不调用任何阻塞代码的挂起函数(仅调用其他挂起函数和非阻塞函数)不需要显式更改dispatchers。