Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active February 12, 2022 06:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manuelvicnt/ea44d3fe8141da46fcb10ce805efe0a3 to your computer and use it in GitHub Desktop.
Save manuelvicnt/ea44d3fe8141da46fcb10ce805efe0a3 to your computer and use it in GitHub Desktop.
class LocationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Listen to one flow in a lifecycle-aware manner using flowWithLifecycle
lifecycleScope.launch {
locationProvider.locationFlow()
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.collect {
// New location! Update the map
}
}
// Listen to multiple flows
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
// As collect is a suspend function, if you want to collect
// multiple flows in parallel, you need to do so in
// different coroutines
launch {
flow1.collect { /* Do something */ }
}
launch {
flow2.collect { /* Do something */ }
}
}
}
}
}
@barbeau
Copy link

barbeau commented May 6, 2021

I believe there is a typo above.

            .flowWithLifecycle(this, Lifecycle.State.STARTED)

...doesn't compile with the error Type mismatch: inferred type is LocationActivity but Lifecycle was expected.

Instead, I believe it should be:

            .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment