Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created June 22, 2021 08:07
Show Gist options
  • Save manuelvicnt/48f573cd4ae2ea5a13a75c337470c34f to your computer and use it in GitHub Desktop.
Save manuelvicnt/48f573cd4ae2ea5a13a75c337470c34f to your computer and use it in GitHub Desktop.
class LocationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val job = lifecycleScope.launch {
doSomeSuspendInitWork()
// DANGEROUS! This API doesn't preserve the calling Context!
// It won't get cancelled when the parent coroutine is cancelled!
addRepeatingJob(Lifecycle.State.STARTED) {
someLocationProvider.locations.collect {
// New location! Update the map
}
}
}
// If something goes wrong, cancel the coroutine launched above
try {
/* ... */
} catch(t: Throwable) {
job.cancel()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment