Brais Gabin
Brais Gabin

Reputation: 5935

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) }
}

Upvotes: 4

Views: 2548

Answers (2)

Glenn Sandoval
Glenn Sandoval

Reputation: 3745

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]

Upvotes: 2

Ilya Zinkovich
Ilya Zinkovich

Reputation: 4430

Use Dispatchers.Unconfined, it's used exactly to run on a current thread.

The whole code will look as follows:

val dispatcher = if (parallel) Dispatcher.Default else Dispatchers.Unconfined

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

Upvotes: 0

Related Questions