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) }
}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With