Executors.newSingleThreadExecutor
queues the tasks registered to it and then executes them sequentially. The following code:
val singleThreadedExecutor = Executors.newSingleThreadExecutor()
(0..10).forEach { i ->
singleThreadedExecutor.execute {
if (i % 2 == 0) {
Thread.sleep(2000)
} else {
Thread.sleep(1000)
}
println(i)
}
}
outputs this:
I/System.out: 0
I/System.out: 1
I/System.out: 2
I/System.out: 3
I/System.out: 4
I/System.out: 5
I/System.out: 6
I/System.out: 7
I/System.out: 8
I/System.out: 9
I/System.out: 10
I want to achieve this behaviour using Kotlin's Coroutines. I have tried using limitedParallelism
but it didn't work as I was expecting. See the code below:
val singleThreadedCoroutine = Dispatchers.Default.limitedParallelism(1)
(0..10).forEach { i ->
lifecycleScope.launch(singleThreadedCoroutine) {
if (i % 2 == 0) {
delay(2000)
} else {
delay(1000)
}
println(i)
}
}
But its output was:
I/System.out: 1
I/System.out: 3
I/System.out: 5
I/System.out: 7
I/System.out: 9
I/System.out: 0
I/System.out: 2
I/System.out: 4
I/System.out: 6
I/System.out: 8
I/System.out: 10
Am I missing something? How can I queue tasks in a coroutine, so that it executes them sequentially?
Thanks.