Suspend functions
Suspendable functions can execute long time operation or call other suspendable functions.
suspend fun load(): User {
// ... long-time operation
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // call other suspend function
return 10
}
Each suspendable function has access to the coroutineContext property.
You can spawn new coroutine within current context via coroutineScope function.
suspend fun doSomethingUsefulTwo(): Int = coroutineScope {
// ...
10
}
To handle exceptions you can wrap a function type by Result class. (Read more about exception in coroutines)
suspend fun doSomething(): Result<Int> = coroutineScope {
runCatching {
// ...
10
}
}
You can compose suspendable functions to execute them sequentially or concurrently.
Concurrent execution is used when tasks are independent of each other. Concurrent execution is faster than sequential execution.
val timeSequential = measureTimeMillis {
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $timeSequential ms")
val timeConcurrent = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $timeConcurrent ms")