How to make multiple launch like multiple thread in kotlin
I want to make that first second are working at the same time forever!!
Like this code...
runBlocking {
// first
launch{
first()
}
// second
launch{
second()
}
}
suspend fun first(){
// do something
delay(1000L)
// Recursive call
first()
}
suspend fun second(){
// do something
delay(1000L)
// Recursive call
second()
}
Your example code would work already, if it is the only running code in your application. If you need those two methods running in parallel to your application, wrap them in GlobalScope.launch:
GlobalScope.launch {
launch { first() }
launch { second() }
}
This will run forever until canceled and/or an exception inside is thrown. If you don't require too many resources inside a coroutine and release them properly when used, you should never have a problem with StackOverFlow.
In addition to recursive code: try to make a loop instead as it is suggested in the comments.
You can implement infinite execution with cycles
runBlocking {
launch { while(true) first() }
launch { while(true) second() }
}
suspend fun first(){
// do something
delay(1000L)
}
suspend fun second(){
// do something
delay(1000L)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With