Show loading progress with a flow – tutorial
The loading functions you've implemented so far return the articles only after all their comments have loaded.
In this part of the tutorial, you'll use a flow to load each article's comments and produce the corresponding Article object. This allows the application to display articles progressively instead of waiting for the complete list.
Flows
A flow represents a sequential stream of values that can be produced asynchronously. Unlike a suspending function, which returns one value, a flow can produce multiple values sequentially over time.
In a flow, the code that produces values is called the emitter, and the code that consumes them is called the collector.
The flow() builder function creates a cold flow. A cold flow starts producing values only when a collector collects it. Each collector starts a new, independent execution of the flow.
Inside a flow() block, use the emit() function to emit values:
To collect the emitted values, use the collect() function. The lambda passed to collect() receives each value:
Task – Implement progress reporting
Open the desktop-client/src/jvmMain/.../articles/tasks/Task4Progress.kt file. It contains the observeArticlesLoading() function with a TODO() placeholder:
Implement the function by adapting the sequential loading logic from the suspending loadArticles() function in the desktop-client/src/jvmMain/.../articles/tasks/Task1BlockVsSuspend.kt file. Load the comments for one article at a time and emit each resulting Article object as soon as its comments have loaded.
Tip for progress reporting
Call service.getArticleInfoList() and store the returned list in a variable named list. Then use a for loop to adapt the Article construction from the suspending loadArticles() function:
Solution for progress reporting
Call the
getArticleInfoList()function and store the returned list.Use a
forloop to process eachArticleInfoobject.For each object:
Call the
getComments()function.Create an
Articleobject from the article information and comments.Use the
emit()function to emit theArticleobject.
The flow emits one Article object after each call to getComments() completes. The collector receives the object immediately and updates the displayed results.
Observe loading progress
Run the application, select WITH_PROGRESS from the Loading Mode menu, and click Load comments.
In this mode, the ArticlesViewModel.loadComments() function calls observeArticlesLoading() and passes the returned Flow<Article> to updateResultsWithProgress():
The observeArticlesLoading() function returns a cold flow, so the application doesn't start loading articles until updateResultsWithProgress() collects it.
Once collection starts, the application requests comments sequentially, so loading all articles still takes approximately 10 seconds. However, it adds each Article object to the displayed results as soon as the flow emits it.

Optional task – Create tests for sequential loading
Turbine is a library for testing Kotlin flows, including the values they emit and how they complete. To see Turbine in action, you'll use it in this task to retrieve emitted values one at a time and verify that the flow completes successfully.
To collect a flow in a Turbine test, call the .test() extension function on it. Inside the lambda passed to .test(), use:
The
awaitItem()function to suspend until the flow emits the next value and retrieve it.The
awaitComplete()function to verify that the flow completes successfully after emitting the expected values.
The .test() function is suspending. To call it from a test, use the runTest() function, which runs the test body in a coroutine.
The runTest() function advances virtual time to skip delays controlled by its test scheduler. This allows the test to complete quickly while preserving the simulated loading duration.
For example, the following test verifies that a flow emits 1, waits for one second using the delay() function, emits 2, and completes successfully:
To measure how much virtual time passes while collecting a flow, use the .measureTime() function with the testScheduler.timeSource property. Inside a runTest() block, this property represents the test scheduler's virtual time and the .measureTime() function returns the elapsed time as a Duration:
Open the desktop-client/src/jvmTest/.../articles/exercises/SequentialTest.kt file. It contains the following test functions with TODO() placeholders:
Implement the tests so that:
The
test observeArticlesLoading Result()function verifies thatobserveArticlesLoading()emits the expectedArticleobjects in order.The
test observeArticlesLoading Duration()function verifies that collecting the flow takes the expected amount of virtual time.
Pass the MockBlogService object to the observeArticlesLoading() function. Use the following test data:
ArticlesFakeDataResults.expectedSequentialList.listcontains the expectedArticleobjects.ArticlesFakeDataResults.expectedSequentialList.durationcontains the expected loading duration.ArticlesFakeData.getArticles().sizeprovides the number of values to retrieve from the flow.
Solution for sequential loading tests
For the test observeArticlesLoading Result() function:
Create a mutable list to store the emitted
Articleobjects.Call the
observeArticlesLoading()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.Use the
assertEquals()function to compare the collected objects withArticlesFakeDataResults.expectedSequentialList.list.Follow the IDE's suggestions to import the necessary symbols.
To implement the test observeArticlesLoading Duration() test:
Import the
measureTime()function from thekotlin.timepackage.Collect the flow inside a
testScheduler.timeSource.measureTime()block and store theDurationit returns.Call the
observeArticlesLoading()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.Use the
assertEquals()function to compare the duration withArticlesFakeDataResults.expectedSequentialList.duration.
Test your implementation
If you completed the optional test-writing exercise, run the tests in the desktop-client/src/jvmTest/.../articles/exercises/SequentialTest.kt file. Otherwise, run the provided tests in the desktop-client/src/jvmTest/.../articles/tasks/Task4ProgressKtTest.kt file.
The tests use the Turbine library to collect and check the flow's emissions. They check that the observeArticlesLoading() function:
Emits the expected
Articleobjects in order.Completes after emitting all the objects.
Takes the expected sequential loading time.
The tests use virtual time, so you don't have to wait for the simulated delays.
In the next part of the tutorial, you'll use channelFlow() to load comments concurrently and emit each Article object when it becomes available.