Skip to content

joost-de-vries/spring-coroutine

Repository files navigation

Kotlin Spring CoroutineScope

Run Kotlin coroutines scoped to a Spring framework bean. Provides a Spring CoroutineScope that hooks into Spring bean lifecycle.

Add compile("it.the-source:dispatcher:0.3") to your dependencies and use it like this

class MySpringBean(dispatcher: CoroutineDispatcher) : MyAbstractBean(), SpringScope by SpringScope(dispatcher) {
    init {
        launch {
            while (true) {
                delay(100.hours)
            }
        }.invokeOnCompletion {
            println("my spring bean is being destroyed")
        }
    }
}

Coroutines started within the Spring bean will be scoped to the lifecycle of the bean. That is they will be cancelled on Spring destroy.
If you want to append additional elements to the scope, use CoroutineScope.plus operator:

val scope = SpringScope() + CoroutineName("MyActivity")

If you want a SupervisorJob parent

class MySpringBean(dispatcher: CoroutineDispatcher) : SpringScope by SpringScope(dispatcher, SupervisorJob()) {

}

If you want to use Dispatchers.Default you can leave out the dispatcher argument

class MySpringBean() : SpringScope by SpringScope() {

}

You can also provide arbitrary coroutine context values:

class MySpringBean() : SpringScope by SpringScope(Dispatchers.Default + SupervisorJob()) {

}

About

Run Kotlin coroutines on Spring Boot taskscheduler

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages