Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created June 22, 2021 08:03
Show Gist options
  • Save manuelvicnt/650b9309ebbc74ca94ca272010f2ae4a to your computer and use it in GitHub Desktop.
Save manuelvicnt/650b9309ebbc74ca94ca272010f2ae4a to your computer and use it in GitHub Desktop.
class LocationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Create a new coroutine from the lifecycleScope
// since repeatOnLifecycle is a suspend function
lifecycleScope.launch {
// Suspend the coroutine until the lifecycle is DESTROYED.
// repeatOnLifecycle launches the block in a new coroutine every time the
// lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
repeatOnLifecycle(Lifecycle.State.STARTED) {
// Safely collect from locations when the lifecycle is STARTED
// and stop collecting when the lifecycle is STOPPED
someLocationProvider.locations.collect {
// New location! Update the map
}
}
// Note: at this point, the lifecycle is DESTROYED!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment