https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zak.taccardi

08/20/2019, 1:18 AM
I have to use an API that accepts an
Executor
as a parameter. How can I create an
Executor
that is backed by
Dispatchers.Default
? There is no
CoroutineDispatcher.asExecutor()
function unfortunately
I don’t want to spin up a new thread unecessarily
a

Adam Powell

08/20/2019, 1:24 AM
what's the rest of the api
specifically that
I added a feature request for it here https://github.com/Kotlin/kotlinx.coroutines/issues/1450
a

Adam Powell

08/20/2019, 1:31 AM
backing it with a dispatcher isn't going to do much for you in terms of bootstrapping into coroutine-world
z

zak.taccardi

08/20/2019, 1:31 AM
I just want the Biometric API to use an already existing thread pool
instead of spinning up a new thread
a

Adam Powell

08/20/2019, 1:32 AM
you can also just use any old handler's
myHandler::post
as an Executor and bounce off the main thread, no need to spin up a different one
if you're processing the results elsewhere you probably want to offer into a channel that you're receiving on or similar instead, from the callback, and just use a directExecutor to do it. It doesn't really matter where the callback is dispatched then
z

zak.taccardi

08/20/2019, 1:34 AM
I’m not sure what you mean by a direct executor
a

Adam Powell

08/20/2019, 1:35 AM
a direct executor is one that just runs an incoming runnable inline without any sort of dispatching
👍 1
z

zak.taccardi

08/20/2019, 1:35 AM
but yeah, I would be sending the results to a channel that would be consumed on the main or a
Dispatchers.Default
thread
a

Adam Powell

08/20/2019, 1:36 AM
if your callback implementation just offers into a channel (or the channel of a
callbackFlow
, or similar) then there's no reason to have the executor bounce between threads an extra time
👍 1
z

zak.taccardi

08/20/2019, 1:37 AM
the UI would consume the channel and send the result to the
ViewModel
which processes intentions/actions on
Dispatchers.Default
a

Adam Powell

08/20/2019, 1:40 AM
whatever you like 🙂 the important part here is that if you're already doing a thread or dispatch hop by sending through a channel or resuming an intercepted continuation, you don't need the Executor to define where the callback should run - it doesn't matter since you're doing your own dispatch into coroutines-land inside the callback itself.
👍 1
z

zak.taccardi

08/20/2019, 1:41 AM
ahh, interesting. the thread the callback executes on doesn’t matter because it will be sent elsewhere anyway 👍
a

Adam Powell

08/20/2019, 1:42 AM
yep
so you might as well use the fastest executor you can (direct) since you can guarantee that the callback won't block the calling thread
👍 1
d

Dico

08/20/2019, 6:43 PM
Copy code
val executor = Executor { 
    GlobalScope.launch { it() }
}
Uses default dispatcher
6 Views