Q:

How to launch corutines in spring applications

I have an app that consumes some messages from a message Queue and processes them. The processing is implemented as suspending functions and there is a service that will publish the events to a Channel<Event>, I have another service that will basically do:
for (event in channel) {
   eventProcessor.process(event)
}

The problem is that this is also a suspending function, and I am really not sure what's the proper way to launch it within the context of Spring.
My initial solution was to do the following: 
@Bean
fun myProcessor(eventProcessor: EventProcessor, channel: Channel<Event>): Job {
GlobalScope.launch {
  eventProcessor.startProcessing(channel)
}
}

But it seems somehow hacky, and I am not sure what's the proper way to do it.

A:

Launching anything on a GlobalScope is a really bad idea. You loose all advantages of structured concurrency this way.
Instead, make your EventProcessor implement CoroutineScope.
This will force you to specify coroutineContext, so you can use Dispatchers.Default:
override val coroutineContext = Dispatchers.Default

So, the full example will look something like this:
@SpringBootApplication
class SpringKotlinCoroutinesApplication {
    @Bean
    fun myProcessor(eventProcessor: EventProcessor, channel: Channel<Event>): Job {
        return eventProcessor.startProcessing(channel)
    }

    @Bean
    fun p() = EventProcessor()

    @Bean
    fun c() = Channel<Event>()
}

fun main(args: Array<String>) {
    runApplication<SpringKotlinCoroutinesApplication>(*args)
}

class Event

class EventProcessor : CoroutineScope {
    override val coroutineContext = Dispatchers.Default

    fun startProcessing(channel: Channel<Event>) = launch {
        for (e in channel) {
            println(e)
        }
    }
}

