kokojustin
kokojustin

Reputation: 200

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

Upvotes: 3

Views: 6848

Answers (2)

Vitaly Roslov
Vitaly Roslov

Reputation: 323

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

Upvotes: 1

Neo
Neo

Reputation: 2049

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.

Upvotes: 5

Related Questions