Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin Coroutine multiple launch

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() 
}
like image 262
kokojustin Avatar asked Aug 15 '26 03:08

kokojustin


2 Answers

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.

like image 101
Neo Avatar answered Aug 16 '26 15:08

Neo


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)
}

like image 44
Vitaly Roslov Avatar answered Aug 16 '26 15:08

Vitaly Roslov