kotlin coroutines code example
Example 1: coroutines kotlin android dependency
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
}
Example 2: 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 3: coroutines dependency
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
Example 4: kotlin coroutines
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch {
doWorld()
}
println("World !")
runBlocking {
delay(4000L)
}
}
suspend fun doWorld() {
delay(2000L)
println("Hello")
}
Example 5: kotlin coroutine builders
launch - Launches new coroutine without blocking
current thread and returns a reference to the coroutine
as a Job.
runBlocking - Runs new coroutine and blocks current
thread interruptible until its completion.
async - Creates new coroutine and returns its future
result as an implementation of Deferred.
withContext - Change a coroutine context for some
block.
Example 6: 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)