小编Nin*_*ski的帖子

LifecycleScope 中的 Kotlin 协程不会阻塞主线程

我对 ViewModel 中的协程感到困惑。

我的问题很简单:为什么下面的协程看起来没有阻止 UIThread?(协程运行时UI依然流畅)

我的片段就在这里:

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)
                }
            }
        })
    }
Run Code Online (Sandbox Code Playgroud)

这是使用 fetchBusTime 方法拍摄的 ViewModel:

suspend fun fetchBusTime(path: Path): Pair<List<Time>?, List<Time>?> {
        Log.v("fetchBusTimeUI", Thread.currentThread().name) // Main

        // Some …
Run Code Online (Sandbox Code Playgroud)

android mvvm coroutine kotlin

6
推荐指数
1
解决办法
2985
查看次数

标签 统计

android ×1

coroutine ×1

kotlin ×1

mvvm ×1