title: Which CoroutineScope to use for Spring Boot WebFlux endpoint
body: <p>In a Spring Boot WebFlux application we have a number of endpoints (REST and GraphQL) which return a <code>Mono</code> or <code>Flux</code> of something. The code that these endpoints call is all non-blocking, but rather than using reactor we'd like to write all this non-blocking code using Kotlin coroutines. We can use a method such as <code>kotlinx.coroutines.reactor.mono()</code> to wrap our coroutines in a <code>Mono</code> (and the corresponding <code>flux()</code> method for <code>Flux</code> results).</p>
  
  <p>In order to call these methods, though, we first need a <code>CoroutineScope</code> to wrap the whole request (and to handle things like cancelling any child coroutines which our main "entry point" coroutine starts). There seem to be several options here. For example, we could construct a new <code>CoroutineScope</code> and choose a dispatcher, e.g. <code>CoroutineScope(Dispatchers.Default).mono {...</code>. Or we could construct our own class which represents the whole HTTP request, and have that implement <code>CoroutineScope</code>, as shown <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html" rel="nofollow noreferrer">here</a> for an Android <code>Activity</code>.</p>
  
  <p>Implicit within this question is the choice of what thread (or thread pool) the work should be executed on. We could create a thread pool ourselves, but Spring Boot WebFlux has already created its own thread pool for handling HTTP requests in a non-blocking environment, so maybe it's better to try to stay in the current thread (or in that thread pool)? If that is the best way to go, is there a way to get at that thread pool and get the coroutine to run on that?</p>