Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a coroutine Dispatcher for the current thread?

Is it possible to create a Dispatcher for the current thread? Check this sample code as an example of what I want to accomplish:

val dispatcher = if (parallel) {
  Dispatcher.Default
} else {
  // What should I write here so I just use the current thread to run doStuff?
}

val deferredList = list.map {
  async(dispatcher) { doStuff(it) }
}
like image 688
Brais Gabin Avatar asked Oct 16 '25 01:10

Brais Gabin


1 Answers

When you build a coroutine, you're passing a CoroutineContext as argument. If you don't pass anything, the new coroutine is built with the current CoroutineContext (its parent's context).

Instead of a Dispatcher you should aim to a CoroutineContext:

val context = if (parallel) {
    Dispatchers.Default
} else {
    coroutineContext
}

val deferredList = list.map {
    async(context) { doStuff(it) }
}

You can also "extract" every Element of the context individually using the Element type as key:

Job: coroutineContext[Job]

Dispatcher: coroutineContext[ContinuationInterceptor]

ExceptionHandler: coroutineContext[CoroutineExceptionHandler]

Name: coroutineContext[CoroutineName]

like image 160
Glenn Sandoval Avatar answered Oct 17 '25 21:10

Glenn Sandoval