really stupid question, but i can’t find an answer...
# coroutines
r
really stupid question, but i can’t find an answer by googling… Are there any guarantees on order of execution when using a single threaded coroutine dispatcher? e.g.:
Copy code
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val scope = CoroutineScope(dispatcher)

for (i in 1..5) {
    scope.launch {
        println(i)
    }
}
are they guaranteed to be executed in order?
or is the dispatcher randomly picking work?
t
Because your
CoroutineDispatcher
is based on a Java single thread executor, coroutines are executed sequentially, in the order of submission. Note that this is not guaranteed for all
CoroutineDispatcher
implementations.
r
okay, thank you 🙂
i assumed that was the case but i couldn’t find any documentation anywhere stating that that was the case
a
people often will be really cagey about answering this question because if you find yourself relying on the order of resumed continuation execution instead of more explicitly controlling your desired ordering, you're likely to be in for some headaches down the road
g
It's easier to assume that there is no guarantee of sequential execution rather than rely on dispatcher implementation
2
b
Agreed, if you don't want your code to be asynchronous from each other, you should write your code to be sequential in the first place.