Hi, I'm working on an open source Android library ...
# coroutines
l
Hi, I'm working on an open source Android library that makes Camera2 API actually usable (with readable code) thanks to coroutines, and there are some places where it takes a
Handler?
. Since coroutines already have the concept of dispatcher, there's a kind of concept duplication (although
Handler
is single threaded, unlike `CoroutineDispatcher`s). I'd like to avoid this leaking into the API of my library as method parameters, so I'm thinking about putting the
Handler
into the
CoroutineContext
so it can be retrieved by the library. Do you think it's a good usage of
CoroutineContext
ThreadLocal-like abilities?
🧵 1
g
I think it’s good use case for custom coroutine context
👍 2
v
It looks like you need
HandlerContext
with public
Handler
property. Feel free to post your solution when it’s ready, maybe we can improve something in coroutines-android
l
If there was a
handler
property on
HandlerContext
, I'd probably have used it in the past to avoid having to pass an extra
Handler
, but I think I'd not do this today, because it can stop working if you add a
withContext
that switches thread. I'll probably resume my work by the next weekend, I'll give an update on how it went and my struggles if any
Here's what I did: https://github.com/Beepiz/CameraCoroutines/blob/a118d64d708d2de12ff35c6e7940bcce4e66d121/cameracoroutines/src/main/java/com/beepiz/cameracoroutines/extensions/HandlerElement.kt I can then just do
Copy code
val handler = coroutineContext[HandlerElement]?.handler
        ?: illegal("Required Handler was not found in coroutineContext")
provided that
illegal
returns
Nothing
.
I don't think it could be integrated smoothly into
HandlerContext
, especially since I may use it while running the coroutine in another
CoroutineDispatcher
like
CommonPool
,
UI
or the experimental dispatcher (and not the
HandlerThread
) which would replace the
HandlerContext
.