returns the future result as Deferred ‣ Deferred gives the future result or throws exception on cancellation ‣ Deferred is a Job ‣ To get the result from Deferred, call await
in a particular context ‣ CoroutineContext can contain a set of elements ‣ The main elements are Job and Dispatchers ‣ Child inherits parent’s context through CoroutineScope.coroutineContext
pool of threads ‣ Main - Main thread in Android ‣ IO - thread pool for blocking IO tasks ‣ Unconfined - Not confined to a specific thread ‣ newSingleThreadContext - Runs in new thread
or another suspending function ‣ Blocks the coroutine, won’t block current thread ‣ Coroutine builders takes suspending function as parameter CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job
the Job, calling job.cancel() ‣ Computations running within coroutines won’t be cancelled ‣ isActive can be used to check if coroutine is active and continue the execution ‣ Any resource cleanup can be done inside finally {} block
scope.launch { val firstHalf = getFirstHalfScore() val secondHalf = getSecondHalfScore() val totalScore = firstHalf + secondHalf } suspend fun getFirstHalfScore(): Int { delay(1000) return 2 } suspend fun getSecondHalfScore(): Int { delay(1000) return 1 }
used, then when parent is cancelled, all child coroutines will be cancelled automatically scope.launch { launch { //.. } } fun onDestroy() { scope.cancel() }
if one of the them throws an exception ‣ Scoping them within their parent coroutine scope does that ‣ Similarly parent coroutine waits for all of it’s children to complete before it finishes itself