of instructions - Multiple Coroutines or Threads can be executed concurrently - Multiple Coroutines or Threads share resources such as memory Difference : - Coroutine = lightweight Thread - Coroutines run in a Thread
of instructions - Multiple Coroutines or Threads can be executed concurrently - Multiple Coroutines or Threads share resources such as memory Difference : - Coroutine = lightweight Thread - Coroutines run in a Thread Thread Coroutines
as “lightweight threads” • Coroutine is similar to thread • Thread-independent and Suspendable subroutine(subprogram) which can call each-other • An approach to Asynchronous Operations
corresponding coroutine uses for its execution. ◦ Confine (restrict) coroutine execution to a specific thread ◦ Dispatch it to a thread pool ◦ Or let it run unconfined (unrestricted)
standard builder • Uses common pools of shared bg thread 1 Dispatcher.Main • Confined to the Main thread operating with UI objects • Should add corresponding artifact 4 Dispatcher.Unconfined • Unrestricted to any specific thread or pool • Shouldn’t be used normally in code 3 Dispatcher.IO • Uses a shared pool of on-demand created threads • Used for IO tasks 2
coroutine context. 5 newFixedThreadPoolContext • To create private thread pool of fixed size. 6 asCoroutineDispatcher • Extension function to convert Executor to dispatcher. 7
run all business logic/code using GlobalScope.launch? • New Problem: ◦ It still consumes some memory resources while it runs. ◦ Leak!! ◦ What if the code in the coroutine hangs?
coroutine • Every coroutine builder is an extension on CoroutineScope • CoroutineScope provides properties like coroutineContext and it is a set of various elements like Job of the coroutine and its dispatcher • GlobalScope -> CoroutineScope with a lifetime of the whole application.
hell dan branching paths • Suspend Function akan selalu aman dipanggil, biarpun dari main thread • Dispatcher bisa memproses ribuan job, no problem. • Coroutine Scope menjaga tidak ada job yg leak • Better Concurrency -> faster & efficient app
https://www.youtube.com/watch?v=jT2gHPQ4Z1Q - https://medium.com/androiddevelopers/rxjava-to-kotlin-coroutines-1204c896a700 - https://proandroiddev.com/kotlin-coroutines-channels-csp-android-db441400965f - credits to Wahid Nur Rohman ( Android Developer at Bukalapak ) - credits to Andika Pratama ( Android Developer at Bukalapak ) - credits to Esa Firman ( Android Developer at Bukalapak )