Is it possible to obtain a `CoroutineContext` from...
# coroutines
e
Is it possible to obtain a
CoroutineContext
from
Thread.currentThread()
? I don't control the current thread instance, but I want to specifically switch to it using e.g.
withContext(/*..*/) {}
.
m
I guess you could make a CoroutineDispatcher that dispatches to this thread.
Mmmm but then if your thread is already started, you can't really submit tasks to it
This thread would need to have a task queue or other loop (like an executor for an example)
e
Maybe I can use
fun <T> ThreadLocal<T>.asContextElement(value: T = get()): ThreadContextElement<T>
instead
m
I'm not sure. In order to "switch" a coroutine to another thread, you'll have to dispatch
e
Because I'm trying to work with a thread-confined class on the IO dispatcher. I think that when a coroutine suspends on that dispatcher, when it later resumes there is no guarantee that it will resume on the same thread
m
Yea,
<http://Dispatchers.IO|Dispatchers.IO>
has multiple threads
e
I'm also still considering just using a single threaded context for simplicity, there might be other concurrency issues with multiple threads, even if I manage to constrain coroutine access to just 1 thread in the IO dispatcher
m
You'll need to create your dispatcher with only one thread and touch your class only from this thread. Maybe something like:
Copy code
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
e
Also, my idea likely breaks some efficiency measures of the IO dispatcher
Thanks for thinking along!
👍 1