Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javent - Coroutines 101

Javent - Coroutines 101

Coroutines 101

Android VIP

April 13, 2019
Tweet

More Decks by Android VIP

Other Decks in Programming

Transcript

  1. Kotlin’s Coroutine 101 How to achieve scalable Asynchronous Programming 1

    By : Javentira Lienata (Android Developer at Bukalapak)
  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 )
  3. Agenda • Introduction ◦ What is Coroutine? ◦ Why Coroutine?

    • Basic and Practices ◦ Suspend Functions ◦ Coroutine Builder ◦ Job ◦ Coroutine Dispatcher ◦ Structured Concurrency ◦ Coroutine Scope 4
  4. What is Coroutine? 6 • The Kotlin team defines coroutines

    as “lightweight threads” • Coroutine is similar to thread
  5. 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
  6. 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
  7. 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
  8. Why Coroutine? 11 • Long Blocking task should be executed

    asynchronously • Possible solutions: - Threading - Callbacks - Futures / Promises - Reactive Extensions
  9. Why Coroutine? 12 • Long Blocking task should be executed

    asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks - Futures / Promises - Reactive Extensions
  10. 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
  11. 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
  12. 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
  13. 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 )
  14. Suspend Functions 19 • Marked with suspend modifier • Suspend

    the execution of the code without blocking the current thread of execution
  15. Suspend Functions 20 • Marked with suspend modifier • Suspend

    the execution of the code without blocking the current thread of execution
  16. 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
  17. 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
  18. 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)
  19. 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
  20. 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
  21. Coroutine Dispatcher 32 Notes : • Launch and async accept

    optional dispatcher • Launch(Dispatchers.Default) { … } uses the same dispatcher as GlobalScope.launch { … }
  22. 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?
  23. Structured Concurrencies 39 Solution 1 Store the job, and cancel

    it on certain lifecycle Well… Don’t you think it’s too complicated?
  24. Coroutine Scope 42 Solution 2 Use Coroutine Scope in some

    local Scope like UI Element with well defined lifecycle
  25. 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.
  26. 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
  27. 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 )