Concurrent loading – tutorial
In the previous part, you kept the application responsive while loading articles, but the comment requests still ran one at a time.
Coroutines can run concurrently with other coroutines and potentially in parallel. In this part of the tutorial, you'll use multiple coroutines to request comments concurrently and reduce the total loading time.
Concurrent coroutines
Two operations run concurrently when one can start before the other has finished. On the JVM, coroutines can run concurrently on the same thread. When a coroutine suspends, it stops using the thread until it can continue, allowing another coroutine to run on that thread.
To load comments concurrently, the implementation you'll write starts a separate coroutine for each ArticleInfo object returned by the getArticleInfoList() function. Each coroutine calls the getComments(articleInfo) function to request that article's comments. When one coroutine suspends while waiting for a response, the UI thread can run another coroutine and schedule the next HTTP request for execution.
This allows multiple HTTP requests to remain in progress at the same time, even though the coroutines execute one at a time on the UI thread.
Coroutine scopes and structured concurrency
When you start multiple coroutines, you need a way to manage them as a group. The principle of structured concurrency connects each child coroutine to the scope in which you start it, so you can manage them together.
You can use the coroutineScope() coroutine builder function to create a CoroutineScope. This function takes a suspending lambda and uses the created CoroutineScope as the lambda's receiver, allowing you to start child coroutines in that scope.
For example, the following function calls the .launch() coroutine builder function twice on this scope to start two child coroutines. Each child calls the delay() function, which suspends the child coroutine for a specified Duration without blocking the thread. To express the durations in seconds, import the seconds extension property from the kotlin.time package:
The first child coroutine resumes and prints Hello before the second resumes and prints World. The printMessages() function returns only after both child coroutines complete.
Return values from coroutines
In addition to the .launch() coroutine builder function, you can use the .async() function to start a coroutine.
Since they are both extension functions on CoroutineScope, you can call either function in a coroutineScope() block to start a child coroutine.
Each function serves different purposes:
Use
.launch()when the coroutine doesn't need to produce a result. It returns aJobhandle that represents the coroutine.Use
.async()when the coroutine needs to produce a result. It returns aDeferredhandle that represents a result that becomes available when the coroutine completes.
To retrieve the result of a coroutine started with the .async() function, use the await() function. If the result isn't available yet, the await() function suspends until the coroutine completes and then returns the result:
You can also retrieve results from multiple Deferred handles with the .awaitAll() extension function. The .awaitAll() function suspends until all the coroutines complete and returns their results as a list:
Task – Implement concurrent loading
Open the desktop-client/src/jvmMain/.../articles/tasks/Task2SequentialVsAsynchronous.kt file.
It contains the loadArticlesConcurrently() function with a TODO() placeholder:
Implement the function by adapting the suspending loadArticles() function from the Task1BlockVsSuspend.kt file. Load the comments for different ArticleInfo objects concurrently and return the resulting Article objects after all HTTP requests have completed.
Tip for concurrent loading
The loadArticlesConcurrently() function already creates a CoroutineScope with the coroutineScope() function. Copy the loading logic from the suspending loadArticles() function into its block, then use .async() to start a child coroutine for each ArticleInfo object.
Base your solution on the following structure:
Solution for concurrent loading
Here's an example solution:
Call the
getArticleInfoList()function to request the availableArticleInfoobjects.Use the
.map()extension function to transform eachArticleInfoobject into aDeferred<Article>handle:Call the
.async()function to start a child coroutine.In the coroutine, call the
getComments()function and create anArticleobject from the article information and comments.
Call the
.awaitAll()extension function on the resulting list ofDeferred<Article>handles.Return the
List<Article>produced by.awaitAll()after all the child coroutines complete.
Observe concurrent loading
Run the application, select CONCURRENT from the Loading Mode menu, and click Load comments.
The application sends each HTTP request without waiting for the previous response. While one coroutine waits for a response, another coroutine can call the getComments() function for another ArticleInfo object.
Loading now takes approximately two seconds instead of ten seconds. The requests remain in progress concurrently, so the longest simulated delay determines the total loading time instead of the sum of all delays.

Test your implementation
Run the tests in the desktop-client/src/jvmTest/.../articles/tasks/Task2SequentialVsAsynchronousKtTest.kt file.
The tests check that the loadArticlesConcurrently() function returns the expected Article objects. They also check that loading takes two seconds of virtual time, which matches the longest possible simulated delay.
In the next part of the tutorial, you'll explore how structured concurrency keeps concurrent loading cancelable.