Daniel Pitts
12/13/2023, 9:15 PMDaniel Pitts
12/13/2023, 9:16 PMDaniel Pitts
12/13/2023, 9:24 PMThreadLocal
, but in a JNI library there is thread-local context.Sam
12/14/2023, 8:51 AMnewSingleThreadContext()
is the right way if you want to create a new dedicated thread for your coroutine to run on. There could be other ways to do it if you want to run the coroutines on some existing thread that already exists in your application, though. For example:
• runBlocking
takes control of its calling thread, and creates an event loop dispatcher to run coroutines on that thread.
• Android's Handler.asCoroutineDispatcher()
will dispatch coroutines to the looper of an existing Handler
.
• Executor.asCoroutineDispatcher()
will dispatch coroutines to any existing executor in your application.Sam
12/14/2023, 8:53 AMSam
12/14/2023, 8:56 AMThreadContextElement
and CopyableThreadContextElement
. These will be invoked every time the coroutine is dispatched to a thread. If you can access and control the thread context you want to set, you could write a ThreadContextElement
to move it from thread to thread as the coroutine is dispatched. The slf4j coroutines integration uses this approach to copy the MDC.Daniel Pitts
12/14/2023, 3:02 PM