Spot the bug
After returning from the back stack, every update is handled twice. Which line is the bug?
class FeedFragment : Fragment() {private val vm: FeedViewModel by viewModels()override fun onViewCreated(view: View, savedInstanceState: Bundle?) {lifecycleScope.launch {vm.items.collect { render(it) }}}}
Hint 1 of 1
Which lifecycle ends when the view is destroyed?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 4
lifecycleScope.launch {
The Fragment's own lifecycleScope lives on while the view is destroyed, so a second collector is added when the view is recreated. Use viewLifecycleOwner.lifecycleScope with repeatOnLifecycle(STARTED).