suited when a result is needed Scope.async { ... } What are coroutine builders? serve as extensions to CoroutineScope gives you more control over lifecycle and behaviour of a coroutine return a Job Functions which are used to launch coroutines
main() { val job = GlobalScope.launch { println("Searching for a Book") } val job2 = GlobalScope.async { println("Currently in the Library") delay(1000) "Found : Kotlin In Action Edition 2" } println(job) println(job2) println("-".repeat(20)) println(job2.await()) Thread.sleep(2000) } "coroutine#1":StandaloneCoroutine{Active}@5479e3f "coroutine#2":DeferredCoroutine{Active}@42f30e0a -------------------- Currently in the Library Searching for a Book Found : Kotlin In Action Edition 2 06
cancellable task needed to run job What's a coroutine context? represented CoroutineContext interface contain a Job and Dispatcher used to execute the coroutine Immutable key-value pair that contains various data available to the coroutine
println("I'm working in thread ${Thread.currentThread().name}") } fun main() = runBlocking<Unit> { launch { working() } launch(Dispatchers.Unconfined) { working() } launch(Dispatchers.Default) { working() } launch(CoroutineName("MyOwnThread")) { working() } } I'm working in thread main @coroutine#3 I'm working in thread DefaultDispatcher-worker-1 @coroutine#4 I'm working in thread main @coroutine#2 I'm working in thread main @MyOwnThread#5 06
thread Changing the context in which a coroutine runs Example import kotlinx.coroutines.* suspend fun main(){ doNetworkStuff() } suspend fun updateUi(){ withContext(Dispatchers.Main){ ... } } suspend fun doNetworkStuff(){ withContext(Dispatchers.IO){ ... updateUi() } }
jobs? track task states and cancel check if isActive, isCancelled, isCompleted The lifecycle of the concurrent task active started but not completed completing waiting for children to complete completed finished and completed children
main() { val job = GlobalScope.launch { var i = 1 while(isActive){ println("Value : ${i++}") } } delay(20) job.cancel() } -------------------------------------- Value : 1 Value : 2 Value : 3 Value : 4 Value : 5 ... 06