-
-
Save ryanamaral/b12539077e9b6ebaccaf2c7c97a1a70e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 */ } | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A safer way to collect flows from Android UIs by Manuel Vivo