Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting multiple flows into one

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.

like image 214
Ankit Verma Avatar asked Oct 23 '25 07:10

Ankit Verma


1 Answers

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() }.

like image 190
Arpit Shukla Avatar answered Oct 24 '25 20:10

Arpit Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!