How can I run multiple coroutine
sequentially(like the order they were called ) inside a coroutine
. I am creating multiple coroutine
inside a coroutine
, I want sequential execution as the order they are called.
Here is my sample code.
fun main(){
runBlocking {
Launch().run()
}
}
class Launch {
fun run(){
for (i in 1..10){
println("Starting $i")
GlobalScope.launch {
println("working id $i")
}
}
}
}
and output is
Starting 1
Starting 2
Starting 3
Starting 4
Starting 5
Starting 6
Starting 7
Starting 8
working id 5
working id 4
working id 3
Starting 9
working id 1
Starting 10
working id 2
working id 8
working id 7
working id 6
working id 9
working id 10
Inside the loop all coroutine
are executing asynchronously, I know it's natural behavior of coroutine. But I want to execute all the coroutine sequentially how can I do that?
Edit:
Its not duplicate
This question answer does not answer my question.
That answer works for one block execution at a time, but don't maintain order. I need to maintain execution order as like they called
Tried with suggested approach
fun main(){
runBlocking {
// Launch().run()
Launch().complex()
delay(1000)
println("Finish")
}
}
class Launch {
private val lock = Mutex()
private fun func(name:String) {
println("method $name")
GlobalScope.launch {
lock.withLock {
println("$name started")
println("$name completed")
}
}
}
fun complex() {
func("1")
func("2")
func("3")
func("4")
func("5")
}
}
Output:
method 1
method 2
method 3
method 4
method 5
1 started
1 completed
3 started
3 completed
4 started
4 completed
2 started
2 completed
5 started
5 completed
Finish
Please check that after 1 completed, 3 is started but call order was 1,2,3,4,5
, that means execution order is not maintained as the called with GlobalScope.launch
I want to execute as the order they were called.
Expected output :
method 1
method 2
method 3
method 4
method 5
1 started
1 completed
2 started
2 completed
3 started
3 completed
4 started
4 completed
5 started
5 completed
Finish