Share
Embed
Transcript
47 slides
-
Kotlin’s Coroutine 101 How to achieve scalable Asynchronous Programming 1
By : Javentira Lienata (Android Developer at Bukalapak) -
HELLO! I am Javentira Lienata one of Bukalapak’s Android Devs
I am here because sharing is caring. 2 -
Career History 3 • AnalisaDaily.com Web Developer ( 2015 -
2016 ) • AjoMedan.com (Daily Deals) Managing Director ( 2015 - 2016 ) • Paprika MultiMedia Web Developer ( 2016 ) • Paprika MultiMedia Mobile Apps Developer Java and React Native ( 2016 - 2017 ) • Bukalapak Mobile Apps Developer ( 2017 - Present ) -
Agenda • Introduction ◦ What is Coroutine? ◦ Why Coroutine?
• Basic and Practices ◦ Suspend Functions ◦ Coroutine Builder ◦ Job ◦ Coroutine Dispatcher ◦ Structured Concurrency ◦ Coroutine Scope 4 -
What is Coroutine? 6 • The Kotlin team defines coroutines
as “lightweight threads” • Coroutine is similar to thread -
Coroutine Vs Thread 7 Similarity : - Both are sequence
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 -
Coroutine Vs Thread 8 Similarity : - Both are sequence
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 -
What is Coroutine? 9 • The Kotlin team defines coroutines
as “lightweight threads” • Coroutine is similar to thread • Thread-independent and Suspendable subroutine(subprogram) which can call each-other • An approach to Asynchronous Programming -
Why Coroutine? 11 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading - Callbacks - Futures / Promises - Reactive Extensions -
Why Coroutine? 12 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks - Futures / Promises - Reactive Extensions -
Why Coroutine? 13 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks ( difficult to understand, callback hell, can’t handle exception ) - Futures / Promises - Reactive Extensions -
Why Coroutine? 15 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks ( difficult to understand, callback hell, can’t handle exception ) - Futures / Promises - Reactive Extensions -
Why Coroutine? 16 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks ( difficult to understand, callback hell, can’t handle exception ) - Futures / Promises ( easier than callback, but still can’t handle leak? ) - Reactive Extensions -
Why Coroutine? 17 • Long Blocking task should be executed
asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks ( difficult to understand, callback hell, can’t handle exception ) - Futures / Promises ( easier than callback, but still can’t handle leak? ) - Reactive Extensions ( steep learning curve, coroutines are easier to understand ) -
Suspend Functions 19 • Marked with suspend modifier • Suspend
the execution of the code without blocking the current thread of execution -
Suspend Functions 20 • Marked with suspend modifier • Suspend
the execution of the code without blocking the current thread of execution -
Coroutine Builder 23 launch • Fire and forget • Doesn’t
have any result • Returns Job 1 async • Fire and gives result • Returns Deferred 2 runBlocking • Blocks current thread 3 -
Job 27 Job • Cancelable thing • Has a life-cycle
• Destroys when its complete Deferred • Implement Job • Light-weight non-blocking future • await()to wait the result -
Coroutine Dispatcher 29 • Determines what thread or threads the
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) -
Coroutine Dispatcher 30 Dispatcher.Default • Used by default in all
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 Dispatcher 31 newSingleThreadContext • To create new private single-threaded
coroutine context. 5 newFixedThreadPoolContext • To create private thread pool of fixed size. 6 asCoroutineDispatcher • Extension function to convert Executor to dispatcher. 7 -
Coroutine Dispatcher 32 Notes : • Launch and async accept
optional dispatcher • Launch(Dispatchers.Default) { … } uses the same dispatcher as GlobalScope.launch { … } -
35 Coroutine Dispatcher The second println operation prints kotlinx.coroutines.DefaultExecutor because
delay suspends the coroutine using the default scheduler. -
Structured Concurrencies 37 • Coroutines are light weight, How about
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? -
Structured Concurrencies 38 Solution 1 Store the job, and cancel
it on certain lifecycle -
Structured Concurrencies 39 Solution 1 Store the job, and cancel
it on certain lifecycle Well… Don’t you think it’s too complicated? -
Structured Concurrencies 40 Well that’s where Structured Concurrencies in Coroutines
comes in handy. How? By Using…. -
Coroutine Scope 42 Solution 2 Use Coroutine Scope in some
local Scope like UI Element with well defined lifecycle -
Coroutine Scope 43 • We can define scope for each
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. -
Jadi apa saja manfaat Coroutines? 45 • Concurrency tanpa callback
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 -
Resources Link 46 - https://proandroiddev.com/how-to-make-sense-of-kotlin-coroutines-b666c7151b93 - https://www.youtube.com/watch?v=EOjq4OIWKqM - https://www.youtube.com/watch?v=BXwuYykIxbk -
https://www.youtube.com/watch?v=jT2gHPQ4Z1Q - credits to Wahid Nur Rohman ( Android Developer at Bukalapak ) - credits to Andika Pratama ( Android Developer at Bukalapak )