Cody Engel
04/28/2020, 8:47 PMCoroutineScope
which I want to run in the background while it's waiting for updates to be sent via a Channel, but once the update is sent, I want the result to be executed on the main thread. In that case, would I want to use Dispatchers.Main.immediate
, something like this CoroutineScope(Dispatchers.Main.immediate + Job())
?
I think I'm getting a little hung up as I'm not sure when I would have a Scope that doesn't use that dispatcher (since I can launch a suspending function with the scope, but telling it to switch to a different dispatcher, say IO
).Zach Klippenstein (he/him) [MOD]
04/28/2020, 8:54 PMreceive()
on a channel and waiting for a value to come in, you don’t need to use a special dispatcher for that. You can just receive from the channel on the main dispatcher.octylFractal
04/28/2020, 8:55 PMimmediate
dispatcher it might dispatch immediately if the message is also posted from the main thread, but that can be dangerous. if the messages are only sent from non-main threads, then there's no reason to use immediate
Job()
, you don't need to add one explicitly unless you prefer it that way 🙂Cody Engel
04/28/2020, 9:10 PMMainScope()
?Zach Klippenstein (he/him) [MOD]
04/28/2020, 9:52 PMChannel.receive()
is a suspending call, which means it doesn't block the thread, and can thus be invoked from the main thread.Cody Engel
04/28/2020, 10:11 PMreceive
can only be invoked from another suspending function so I need to use CoroutineScope.launch
somewhere.
So from the consumer side it's essentially this:
abstract class FooStatusConsumer(
coroutineScope: CoroutineScope,
channel: Channel<FooStatus> = Channel()
) {
init {
coroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
for (fooStatus in channel) {
withContext(Dispatchers.Main) {
consume(fooStatus)
}
}
}
}
abstract fun consume(fooStatus: FooStatus)
}
octylFractal
04/28/2020, 10:15 PMDispatchers.Main
at the top, drop withContext
?Cody Engel
04/28/2020, 10:18 PMoctylFractal
04/28/2020, 10:33 PMCody Engel
04/28/2020, 10:37 PMlaunch
from a scope then you are good to go. I'm guessing if I wanted to kick off the suspend function from the IO or Default dispatcher that's when I'd use a scope which started with that... But in the majority of practical situations MainScope()
is probably a decent place to startoctylFractal
04/28/2020, 10:38 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
-- whether that be the Main or Default dispatcher depends on which part of the code I'm inZach Klippenstein (he/him) [MOD]
04/28/2020, 10:51 PMCody Engel
04/29/2020, 1:37 PM