-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Description
Use case
Writing an application that gracefully cancels the coroutines when the OS sends a termination signal, so that caches could be flushed, the in-flight data persisted, and so on, before the program stops.
The Shape of the API
At the very least, it should be possible to obtain one root coroutine scope that would get cancelled if a termination signal is raised:
suspend fun main() = kotlinxCoroutinesApp { // this : CoroutineScope
// `this` will be cancelled if the user attempts to shutdown the program
}With this, other scopes like GlobalScope and scopes manually created via CoroutineScope() will not be aware of the signals. Maybe there is another API shape that would cover these use cases as well, but we'd need to dive deeper into the mechanics of termination on all platforms to figure that out.
Prior Art
- https://github.com/arrow-kt/suspendapp implements a similar function.
-
In Scala libraries like ZIO & Cats-effect also come with ZIOApp or IOApp that offers an
def main(args: Array[String]: IO[ExitCode]to allow back-pressuring the termination signal that gets translated into cancellation.