Cancel concurrent loading with structured concurrency – tutorial
Concurrent loading starts several child coroutines to request comments. When loading is no longer needed, the application must be able to stop these coroutines as a group. For example, a user may close a window, navigate away from a screen, or decide to cancel a long-running loading operation before it finishes. In each case, the application can stop the remaining work instead of letting it continue in the background.
In this part of the tutorial, you'll explore the cancellation behavior of coroutines.
Cancel coroutines
A coroutine's Job handle represents its lifecycle and parent-child relationships. You can use it to request to stop a coroutine before it completes.
The .launch() coroutine builder function returns a Job. The .async() coroutine builder function returns a Deferred, which implements Job and supports the same cancellation behavior.
To request cancellation, invoke the cancel() function on the coroutine's Job handle.
In the Articles application, the ArticlesViewModel.loadComments() function stores the Job returned by loadingScope.launch() in the loadingJob property. When you click Cancel, the ArticlesViewModel.cancelLoading() function invokes cancel() on this Job.
Cancellation propagation
In the previous part of the tutorial, the loadArticlesConcurrently() function used coroutineScope() to connect each child coroutine to the parent loading coroutine. Structured concurrency ensures that canceling a coroutine also cancels all its children. This behavior is known as cancellation propagation.
In CONCURRENT mode, each .async() call starts a child coroutine that requests comments for an ArticleInfo object. When the application cancels the parent loading coroutine, cancellation propagates to these child coroutines and stops their work as well.
Suspension points and cancellation
In Kotlin, coroutine cancellation is cooperative. Coroutines react to cancellation when they suspend or check for cancellation explicitly.
When a coroutine is canceled, it continues until it reaches a point where it may suspend, also known as a suspension point. If the coroutine suspends there, the suspending function checks whether it has been canceled. If it has, the coroutine stops and throws a CancellationException.
Each child coroutine in loadArticlesConcurrently() calls the suspending getComments() function. The function can suspend while waiting for an HTTP response, giving the coroutine a suspension point where it can react to cancellation.
When a coroutine is canceled while waiting for an HTTP response, the Ktor client cancels the request. In this project, the local server configures Ktor's HttpRequestLifecycle to cancel the coroutine processing that request.
Start coroutines in GlobalScope
Sometimes, you may want to start a coroutine that continues running for the application's entire lifetime, independently of other coroutines. The GlobalScope object provides a scope that isn't connected to the parent loading coroutine.
A coroutine started with GlobalScope.async() isn't a child of the loading coroutine. Therefore, canceling the loading coroutine doesn't automatically cancel it.
The coroutine can still be canceled by invoking cancel() on its own Deferred handle. However, this doesn't happen automatically through cancellation propagation because starting the coroutine in GlobalScope breaks structured concurrency.
Task – Implement loading with GlobalScope
Open the desktop-client/src/jvmMain/.../articles/tasks/Task3StructuredConcurrency.kt file. It contains the loadArticlesNonCancelable() function with a TODO() placeholder:
Implement the function by adapting the loadArticlesConcurrently() function from the previous task. Start the coroutines that request comments in GlobalScope and return the resulting Article objects after all the coroutines complete.
Solution for loading with GlobalScope
Call the
getArticleInfoList()function and store the returned list.Use the
.map()extension function to process eachArticleInfoobject.Inside
.map(), callGlobalScope.async():Call the
getComments()function.Create an
Articleobject from the article information and comments.
Call the
.awaitAll()extension function on the resulting list and return the completedArticleobjects.
Compare the cancellation behavior
First, run the application and select CONCURRENT from the Loading Mode menu. Click Load comments, then click Cancel before loading finishes.
When you click Cancel, the ArticlesViewModel.cancelLoading() function in the desktop-client/src/jvmMain/.../articles/ui/ArticlesViewModel.kt file invokes cancel() on loadingJob. This property stores the Job returned by the .launch() call in loadComments().
In CONCURRENT mode, cancellation propagates through the coroutine hierarchy to the child coroutines started inside the loadArticlesConcurrently() function. The Ktor client cancels their pending HTTP requests, and the server logs a CANCELLED message for each request:

Next, select NON_CANCELABLE, click Load comments, and click Cancel again.
The application still cancels the parent loading coroutine. However, the coroutines started with GlobalScope.async() aren't its children, so cancellation doesn't propagate to them. As a result, they continue requesting comments after the parent loading coroutine has been canceled, wasting resources in the process:

Test your implementation
Run the tests in the desktop-client/src/jvmTest/.../articles/tasks/Task3StructuredConcurrencyKtTest.kt file.
In IntelliJ IDEA, you can do this by clicking the Run icon in the gutter next to the test class declaration. For more information, see Run tests.
The tests verify that the loadArticlesNonCancelable() function returns the expected Article objects when loading completes. They also verify that the loadArticlesConcurrently() function reacts to cancellation. The test loadArticlesConcurrently Cancellation() function starts loadArticlesConcurrently() in a coroutine, waits for one second of virtual time, and cancels the coroutine's Job. It then checks that the Job is canceled and that cancellation completes before two seconds of virtual time have elapsed.
The tests don't check whether the coroutines started in GlobalScope continue after the parent loading coroutine is canceled.
In the next part of the tutorial, you'll use a flow to report loading progress as each article becomes available.