10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) }
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) }
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) }
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) //prints 518 }
fun getOrders(userId: String): List<Orders> fun fetchUserOrders() { val user = login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) }
User { return withContext(Dispatcher.IO) { //returns User } } suspend fun getOrders(userId: String): List<Orders> { return withContext(Dispatchers.IO) { //return list of orders } }
CoroutineScope • We need to be able to keep track of all coroutines launched • CoroutineScope should be implemented by an object with a lifeycle i.e Activity, Fragment, ViewModel
return immediately and executes its task concurrently with the rest of the program. • Suspending functions should do its task separately in another context and return to caller when done. It should not block the caller.
another context and return to caller when done. It should not block the caller. • Functions should not be both suspending and an extension function on coroutine scope.
IndexOutOfBoundsException() //exception will be printed to console } val deferred = GlobalScope.async { println("Throwing exception from async") throw ArithmeticException() // Nothing is printed, relying on user to call await }
ArithmeticException() // Nothing is printed, relying on user to call await } try { deferred.await() println("Unreached") } catch (e: ArithmeticException) { println("Caught ArithmeticException") //printed to the console }
} val job = GlobalScope.async(exceptionHandler) { throw IndexOutOfBoundsException(“error occurred”) } //exception will be swallowed and nothing printed to the console