Emit values concurrently with channelFlow – tutorial
In the previous part of the tutorial, you used a flow to display articles as their comments loaded. However, the application still requested comments for one article at a time.
In this part, you'll use channelFlow() to load comments for articles concurrently. This way, the application can display each resulting Article object as soon as its comments become available.
Emit values concurrently with the channelFlow() function
The flow() builder function is simple and efficient for flows that emit values sequentially from a single coroutine. To produce values from multiple coroutines concurrently, use the channelFlow() builder function.
Like flow(), channelFlow() creates a cold flow, but it uses a channel to send values from multiple coroutines. Its block provides a CoroutineScope for starting child coroutines and a SendChannel for sending values from them.
Inside a channelFlow() block:
Use the
.launch()coroutine builder function to start child coroutines.Use the
send()function instead ofemit()to produce values.
For example, the following function starts two child coroutines that send values to the same flow:
Because the child coroutines run concurrently, the order in which the collector receives their values isn't guaranteed.
Task – Implement concurrent progress reporting
Open the desktop-client/src/jvmMain/.../articles/tasks/Task5AsyncProgress.kt file. It contains the observeArticlesConcurrently() function with a TODO() placeholder:
Implement the function so that it:
Requests the list of available articles.
Starts a child coroutine for each
ArticleInfoobject.Loads comments for the articles concurrently.
Sends each resulting
Articleobject when its comments have loaded.
Tip for concurrent progress reporting
Use the channelFlow() function to create the flow. Inside its block, use a for loop to start a child coroutine for each ArticleInfo object:
Each child coroutine can call the suspending getComments() function and send the resulting Article object independently.
Solution for concurrent progress reporting
Use the
channelFlow()builder function to create the flow.Call the
getArticleInfoList()function and store the returned list.Use a
forloop to process eachArticleInfoobject.For each object, call the
.launch()coroutine builder function to start a child coroutine that loads its comments.In each child coroutine:
Call the
getComments()function.Create an
Articleobject from the article information and comments.Use the
send()function to send theArticleobject.
Each .launch() call starts a child coroutine that requests comments for one article. After the getComments() function returns the comments, the coroutine creates and sends the corresponding Article object.
Observe concurrent progress
Run the application, select CONCURRENT_WITH_PROGRESS from the Loading Mode menu, and click Load comments.
In this mode, the ArticlesViewModel.loadComments() function calls observeArticlesConcurrently() and passes the returned Flow<Article> to updateResultsWithProgress():
The updateResultsWithProgress() function collects the flow, which starts the channelFlow() block and its child coroutines.
The child coroutines request comments concurrently and send each Article object when its comments become available. The application updates the displayed article list after receiving each object.
Loading takes approximately two seconds, and the articles appear progressively. Because the comment requests take different amounts of time, the order of the displayed articles isn't guaranteed.

Optional task – Create tests for concurrent loading
This exercise builds on the optional test-writing exercise from the previous part of the tutorial. As in the previous exercise, use the Turbine library with the same test structure, using .test(), awaitItem(), awaitComplete(), runTest(), and .measureTime().
Unlike sequential loading, concurrent loading doesn't guarantee the order in which the flow emits its values. To verify the results without requiring a particular order, convert the expected and collected lists to sets with the .toSet() extension function before comparing them.
Like before, you can use the testScheduler.timeSource.measureTime() function to measure the elapsed virtual time. It returns a Duration, so you can compare it directly with ArticlesFakeDataResults.expectedConcurrentList.duration.
To verify that the elapsed time doesn't exceed the expected upper bound, use the assertTrue() function.
Open the desktop-client/src/jvmTest/.../articles/exercises/AsyncProgressTurbineTest.kt file. It contains the following test functions with TODO() placeholders:
Implement the tests so that:
The
test observeArticlesConcurrently Result()function verifies thatobserveArticlesConcurrently()emits all the expectedArticleobjects, regardless of their order.The
test observeArticlesConcurrently Duration()function verifies that collecting the flow completes within the expected concurrent loading time.
Pass the MockBlogService object to the observeArticlesConcurrently() function. Use the following test data:
ArticlesFakeDataResults.expectedConcurrentList.listcontains the expectedArticleobjects.ArticlesFakeDataResults.expectedConcurrentList.durationcontains the upper bound for the loading duration.ArticlesFakeData.getArticles().sizeprovides the number of values to retrieve from the flow.
Solution for concurrent loading tests
For the test observeArticlesConcurrently Result() function:
Create a mutable list to store the emitted
Articleobjects.Call the
observeArticlesConcurrently()function withMockBlogService, then call the.test()extension function on the returned flow.Use the
repeat()function withArticlesFakeData.getArticles().size.During each iteration, call the
awaitItem()function and add the returnedArticleobject to the mutable list.Call the
awaitComplete()function to verify that the flow completes successfully.Convert the expected and collected lists to sets with the
.toSet()extension function.Use the
assertEquals()function to compare the sets.Follow the IDE's suggestions to import the necessary symbols.
To implement the test observeArticlesConcurrently Duration() test:
Collect the flow inside a
testScheduler.timeSource.measureTime()block and store theDurationit returns.Call the
observeArticlesConcurrently()function withMockBlogService, then call the.test()extension function on the returned flow.Use the
repeat()function withArticlesFakeData.getArticles().sizeand call theawaitItem()function during each iteration.Call the
awaitComplete()function to verify that the flow completes successfully.Store
ArticlesFakeDataResults.expectedConcurrentList.durationas the expected upper bound.Use the
assertTrue()function to verify that the elapsed time doesn't exceed the expected upper bound.Import the
assertTrue()function fromkotlin.testand the.measureTime()function fromkotlin.time.
Test your implementation
If you completed the optional test-writing exercise, run the tests in the desktop-client/src/jvmTest/.../articles/exercises/AsyncProgressTurbineTest.kt file. Otherwise, run the tests in the desktop-client/src/jvmTest/.../articles/tasks/Task5AsyncProgressKtTest.kt file.
The tests use the Turbine library to collect the flow and check that the observeArticlesConcurrently() function:
Sends all the expected
Articleobjects, regardless of their order.Completes after sending all the objects.
Completes within the expected concurrent loading time.
The result test compares sets instead of lists because concurrent loading doesn't guarantee the order of the emitted objects.
In the next part of the tutorial, you'll handle exceptions when requests fail because of an unstable network.