2024.1+Launching Coroutines
Edit pageLast modified: 21 February 2025tip
Kotlin Coroutines×IntelliJ PlatformThis section focuses on explaining coroutines in the specific context of the IntelliJ Platform. If you are not experienced with Kotlin Coroutines, it is highly recommended to get familiar with Learning Resources first.
There are two approaches to launching coroutines in the IntelliJ Platform:
Service with its own scope. (recommended)
Launching Coroutine From Service Scope
The recommended approach is creating a service that receives its scope via the constructor injection and launching a coroutine from the service methods. Please note that while creating a service instance does allocate additional resources, using a dedicated service and scope remains a lightweight and, most importantly, safe solution for launching coroutines. It should be used whenever possible.
The pattern is as follows:
@Service
class MyApplicationService(
private val cs: CoroutineScope
) {
fun scheduleSomething() {
cs.launch {
// do something
}
}
}
@Service(Service.Level.PROJECT)
class MyProjectService(
private val project: Project,
private val cs: CoroutineScope
) {
fun scheduleSomething() {
cs.launch {
// do something
}
}
}
The injected scope is created per service, so each instance has its own isolated scope with a common parent, which is an intersection scope. The injected scope is canceled when the container (application/project) is shut down or when the plugin is unloaded.
Using runBlockingCancellable
warning
Using
runBlockingCancellable
is not recommended. Use service scopes whenever possible.
In a standard coroutine-based application, the bridge between the regular blocking code and the suspending code is the runBlocking
function.
In the IntelliJ Platform, a similar purpose is achieved by the runBlockingCancellable
function. In addition to the same semantics as runBlocking
, the action gets canceled when the current progress indicator or the current job is canceled.
note
Something missing?If a topic you are interested in is not covered in the above sections, let us know via the Was this page helpful? feedback form below or other channels.
Please be specific about the topics and reasons for adding them, and leave your email in case we need more details. Thanks for your feedback!
Thanks for your feedback!