Antoine Gagnon
03/26/2021, 5:26 PMZach Klippenstein (he/him) [MOD]
03/26/2021, 5:37 PMprivate val tasks = Channel<suspend () -> Unit>(UNLIMITED)
fun enqueueTask(task: suspend () -> Unit) { tasks.offer(task) }
suspend fun run() {
tasks.consumeEach { task ->
task()
}
}
Antoine Gagnon
03/26/2021, 5:46 PMbaxter
03/26/2021, 9:03 PMfun main() {
scope.launch(Dispatchers.Main) {
dataList().forEach { item ->
withContext(Dispatchers.Default) {
doWorkWith(item)
}
}
}
}
Zach Klippenstein (he/him) [MOD]
03/27/2021, 12:59 AMbaxter
03/27/2021, 1:09 AMflow
and doing the work on an onEach
block is essentially the same as using a Channel.Zach Klippenstein (he/him) [MOD]
03/27/2021, 1:14 AMflow
you mean MutableSharedFlow
, then yesbaxter
03/27/2021, 3:05 AMDispatchQueue
is conceptually a Channel
in iOS. I was thinking it was already a cold list of items, which is why I mentioned using flow with it. 😅
For those following along, if you have a cold list of items to run, you can do something such as list.asFlow().onEach { withContext(<http://Dispatchers.IO|Dispatchers.IO>) { /*.. do work ..*/ } }.launchIn(scope)
to do work sequentially on another thread .
You could also use MutableSharedFlow
to send items to a flow and have them run sequentially, and can be multi-cast. Just be aware of the back pressure strategy you use.Channel
would be the closest to DispatchQueue
.