I am collecting data from datastore in flows in nested launch{}.
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
launch {
DataStore.userName.collect {
// it emits string value
Log.e(TAG, it )
}
}
launch {
DataStore.userPhone.collect {
// it emits string value
Log.e(TAG, it )
}
}
launch {
DataStore.userAddress.collect {
// it emits string value
Log.e(TAG, it )
}
}
}
Is there a better way to collect flows in fragments ? Like collecting all data in single launch{} block.
One option is to combine all flows like this:
combine(DataStore.userName, DataStore.userPhone, DataStore.userAddress) { userName, userPhone, userAddress ->
// Operate on these values
}
Another option can be to use launchIn which launches the collection of flow in provided coroutine scope.
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
DataStore.userName.onEach { userName ->
// ...
}.launchIn(this)
DataStore.userPhone.onEach { userPhone ->
// ...
}.launchIn(this)
DataStore.userAddress.onEach { userAddress ->
// ...
}.launchIn(this)
}
launchIn is just a shorthand for scope.launch { flow.collect() }.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With