Pick the fix
Location updates keep flowing while the app is in the background. What fixes it?
class MapActivity : ComponentActivity() {
private val vm: MapViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
vm.locations.collect { render(it) }
}
}
}Hint 1 of 1
Which lifecycle state means the screen is visible?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Wrap the collect in repeatOnLifecycle(Lifecycle.State.STARTED)
Correct. Collection stops in the background and restarts when the screen is visible.
Why not the others?
- B Use
GlobalScope.launchinstead. That never stops, even after the Activity is destroyed. - C Add
.flowOn(Dispatchers.IO). That changes the producer's thread, not when it runs. - D Call
collectinsideonResume. Each resume would start another collector and none would stop.