英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论