使用`lifecycleScope.launch {}`的时机是:

huangapple go评论64阅读模式
英文:

When to use lifecycleScope.launch {}

问题

我不清楚何时以及为什么我们需要使用 lifecycleScope.launch {}

我理解这不会阻塞UI线程,但如果你正在进行UI工作,难道不应该在UI线程上进行吗?

那些在UI启动时每次调用的回调呢?

你需要在片段的 onViewCreated 中使用这个吗?或者在活动的 onResume 中呢?

英文:

I'm not clear on when and why we need to use lifecycleScope.launch {}

I understand that this doesn't block the UI thread, but if you are doing UI work shouldn't you be doing it on the UIThread?

What about callbacks that are called everytime the UI is launch

Would you need to use this in a fragment's onViewCreated? Or what about an Activities onResume?

答案1

得分: 2

lifecycleScope 是在活动和碎片中使用的协程范围(对于碎片,应该使用 viewLifecycleOwner.lifecycleScope),由 lifecycleScope 启动的每个协程都将在调用 onDestroy() 时停止。

英文:

lifecycleScope is a coroutine scope that's used in activities and fragments (you should use viewLifecycleOwner.lifecycleScope for fragments), every coroutine launched by lifecycleScope will be stopped when onDestroy() is called.

huangapple
  • 本文由 发表于 2023年7月10日 11:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定