coroutine kotlin code example
Example 1: kotlin coroutine scope
CoroutineScope
To start coroutine scope you can:
Use GlobalScope that has empty coroutine context.
Implement CoroutineScope interface.
Create a scope from a context:
with(CoroutineScope(context = context)) { ... }
Example 2: kotlin coroutines
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch {
doWorld()
}
println("World !")
runBlocking {
delay(4000L)
}
}
suspend fun doWorld() {
delay(2000L)
println("Hello")
}
Example 3: kotlin coroutine channel
Channels
fun CoroutineScope.produceSquares():
ReceiveChannel<Int> = produce {
for (x in 1..5) send(x * x)
}
val squares = produceSquares()
repeat(5) { println(squares.receive()) }
val squares2 = produceSquares()
for(square in squares2) print(square)