Skip to content

Instantly share code, notes, and snippets.

@ryanamaral
Forked from manuelvicnt/FlowWithLifecycleUsage.kt
Created February 12, 2022 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanamaral/b12539077e9b6ebaccaf2c7c97a1a70e to your computer and use it in GitHub Desktop.
Save ryanamaral/b12539077e9b6ebaccaf2c7c97a1a70e 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 */ }
}
}
}
}
}
@ryanamaral
Copy link
Author

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