Replace blocking calls with suspending functions – tutorial
In this part of the tutorial, you'll implement two strategies for loading articles and their comments. First, you'll send requests synchronously from the thread that updates the interface and handles user input, also known as the UI thread.
You'll observe how blocking this thread negatively affects the application. Then, you'll send the same requests with suspending functions so that the application remains responsive while waiting for data.
Explore the article-loading task
Open the desktop-client/src/jvmMain/kotlin/org/example/articles/tasks/Task1BlockVsSuspend.kt file. It contains two loadArticles() functions with TODO() placeholders:
The application invokes the corresponding loadArticles() function based on the selected loading mode:
BLOCKING invokes the function with the
BlogServiceBlockingparameter.SUSPENDING invokes the suspending function with the
BlogServiceparameter.
The loadArticles() functions create and return instances of the Article data class. Each instance combines an ArticleInfo object with a list of instances of the Comment data class. These data classes are declared in the following files:
The
shared/src/main/kotlin/org/example/blog/ArticleInfo.ktfile contains:ArticleInfo, which stores an article's ID, author, and title.Comment, which stores a comment's author and content.
The
desktop-client/src/jvmMain/kotlin/org/example/articles/model/Article.ktfile contains theArticledata class, which combines anArticleInfoobject with its comments:Article(info: ArticleInfo, comments: List<Comment>).
Blocking requests
An application can become unresponsive when it has to wait for an operation to finish before it can handle other work.
On the JVM, applications use threads to perform work. If the thread responsible for handling user interactions has to wait for an operation to finish, it can't do other work in the meantime. An operation that causes the thread to wait in this way is known as a blocking operation.
The BlogServiceBlocking class in the network/BlogServiceBlocking.kt file uses the blocking API from the Retrofit library to perform HTTP requests.
For the blocking implementation, you'll use the following functions:
getArticleInfoList()to request the list of available articles.getComments(articleInfo: ArticleInfo)to request the comments for the specifiedArticleInfo.
For example, its getArticleInfoList() function contains the following code:
The getArticlesCall() function prepares an HTTP request. The execute() function sends the request and blocks the current thread until the server returns a response.
Task – Implement the blocking function
In the Task1BlockVsSuspend.kt file, find the following TODO() placeholder function:
Replace the TODO() placeholder with code that:
Loads the available
ArticleInfoobjects.Loads the comments for each article.
Combines each
ArticleInfoobject with its comments.Returns the resulting
Articleobjects.
Solution for the blocking function
Call the
getArticleInfoList()function and store the returned list.Use the
.map()extension function to process eachArticleInfoobject:Call the
getComments()function to load its comments.Combine the
ArticleInfoobject and its comments into anArticleobject.
Return the list produced by
.map().
Observe the blocking behavior
Run the application, select BLOCKING from the Loading Mode menu, and click Load comments.
To simulate real-world network latency, the local server delays its response to each request for comments by 0.25 to 2 seconds. The blocking implementation loads comments for one article at a time, so these delays can add up to approximately 10 seconds.
The application invokes the blocking loadArticles() function on the UI thread. To load the articles and comments, BlogServiceBlocking invokes Retrofit's execute() function for each HTTP request. The UI thread can't update the window or handle input until loadArticles() returns. As a result, the rotating emoji stops and the application remains unresponsive until all articles and comments have loaded. With this behavior, you clearly see why blocking operations are a poor fit for the UI thread and why loading data in real-world applications requires a different approach.

Suspending functions
As an alternative, Kotlin provides suspending functions, which can pause at a suspension point without blocking the thread and continue later from that point. You can only call a suspending function from another suspending function.
To declare a suspending function, use the suspend keyword:
The BlogService interface in the network/BlogService.kt file declares getArticleInfoList() and getComments() as suspending functions. The private BlogServiceImpl class implements these functions with Ktor, such as in the getArticleInfoList() function:
Ktor's suspending .get() extension function sends the HTTP request. While waiting for a response, the getArticleInfoList() function can suspend its execution without blocking the thread. When the server returns a response, the function continues.
The suspend keyword alone doesn't make blocking code non-blocking. It declares a function as suspending, which allows the function to call other suspending functions. Because getArticleInfoList() and getComments() are suspending functions, the second loadArticles() function also uses the suspend keyword.
Coroutines
A coroutine is a suspendable computation that can pause and resume execution. On the JVM, coroutines run on threads and can be suspended. When a coroutine is suspended, the corresponding computation is paused, removed from the thread, and stored in memory. Meanwhile, the thread is free to run other tasks:

New coroutines are launched in a CoroutineScope. A CoroutineScope defines the context in which its coroutines run and manages their lifecycle.
To start a coroutine, use a coroutine builder function such as .launch(). The .launch() builder function accepts a suspending lambda that contains the code for the new coroutine. Inside this lambda, you can call suspending functions.
In this project, loadingScope is the CoroutineScope used for loading articles. Each time you click Load comments, the ArticlesViewModel.loadComments() function in the desktop-client/src/jvmMain/.../articles/ui/ArticlesViewModel.kt file calls the .launch() coroutine builder function and runs the selected loading mode inside it:
Because .launch() takes a suspending lambda, it can call the suspending loadArticles(service) function.
Task — Implement the suspending function
In the Task1BlockVsSuspend.kt file, replace the TODO() placeholder in the following function:
Using the same loading process as in the blocking implementation, replace the TODO() placeholder with code that:
Loads the available
ArticleInfoobjects.Loads the comments for each article.
Combines each
ArticleInfoobject with its comments.Returns the resulting
Articleobjects.
Solution for the suspending function
Call the suspending
getArticleInfoList()function and store the returned list.Use the
.map()extension function to process eachArticleInfoobject:Call the suspending
getComments()function to load its comments.Combine the
ArticleInfoobject and its comments into anArticleobject.
Return the list produced by
.map().
Observe the suspending behavior
Run the application, select SUSPENDING from the Loading Mode menu, and click Load comments.
Even though the suspending loadArticles() function follows the same loading logic as the blocking version, it doesn't block the UI thread while waiting for responses. Its calls to getArticleInfoList() and getComments() can suspend, allowing the application to remain responsive. You can see this in the application, where the emoji continues rotating while the articles and comments load. Loading still takes approximately 10 seconds because the application requests comments sequentially, one article at a time.

Test your implementation
Run the tests in the desktop-client/src/jvmTest/.../articles/tasks/Task1BlockVsSuspendKtTest.kt file.
In IntelliJ IDEA, click the Run icon in the gutter next to the test class declaration.
The tests check that the suspending loadArticles() function returns the expected Article objects and loads their comments sequentially. They use virtual time, so you don't have to wait for the simulated delays.
Congratulations! You've completed the first part of this tutorial.
By switching to an implementation based on suspending functions, you've freed the UI thread to perform other meaningful work without changing the loading logic.
In the next part of the tutorial, you'll send the comment requests concurrently to reduce the total loading time.