czuckie
11/30/2022, 12:52 AMval executor = Executors.singleThreadExecutor()
fun oneAtATime(workToDo: Boop) {
return executor.submit {
doSomethingWIthThe(workToDo)
}.get()
}
Where oneAtATime(...)
may be invoked by multiple threads, but will only allow one operation at a time due to the single thread executor.czuckie
11/30/2022, 12:54 AM.asCoroutineDispatcher
?Joffrey
11/30/2022, 12:55 AMwithContext()
and pass a single thread dispatcher (no need for a coroutine scope, just a dispatcher). However, if what you want is mutual exclusion, you should probably just use a Mutex
and protect the piece of code with mutex.withLock { ... }
czuckie
11/30/2022, 12:57 AMephemient
11/30/2022, 1:10 AMprivate val workQueue = MutableSharedFlow<Boop>()
private val worker = scope.launch {
workQueue.collect { workToDo ->
doSomethingWithThe(workToDo)
}
}
suspend fun oneAtATime(workToDo: Boop) {
workQueue.emit(workToDo)
}
which makes it more obvious that the work is being processed sequentially and uniformly, without requiring additional lockingJoffrey
11/30/2022, 1:12 AMoneAtATime()
but you're right, in the OP there is no such result, which makes it possible to just enqueue asynchronouslyephemient
11/30/2022, 1:13 AMUnit
return type which is missing in the example, in which case your proposal is betterDmitry Khalanskiy [JB]
11/30/2022, 9:24 AMlimitedParallelism
on a dispatcher of your choice? https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/limited-parallelism.html
val dispatcher = Dispatchers.Default.limitedParallelism(1)
suspend fun oneAtATime(workToDo: Boop) = withContext(dispatcher) {
doSomethingWIthThe(workToDo)
}
czuckie
11/30/2022, 10:09 AMephemient
11/30/2022, 4:41 PMdoSomethingWithThe()
function does. if it requires parallelism internally, that's a problem, but if it's just a blocking call then you're fineuli
11/30/2022, 8:06 PM