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

Kotlin Coroutines 101

Kotlin Coroutines 101

Asynchronous and Better Concurrency in Kotlin

Javentira Lienata

April 13, 2019
Tweet

Other Decks in Programming

Transcript

  1. Kotlin’s Coroutine 101 Asynchronous and Better Concurrency in Kotlin 1

    By : Javentira Lienata (Android Developer at Bukalapak)
  2. Career History 4 • 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 5
  4. What is Coroutine? 7 • The Kotlin team defines coroutines

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

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

    asynchronously • Possible solutions: - Threading ( expensive ) - Callbacks - Futures / Promises - Reactive Extensions
  10. Why Coroutine? 23 • 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? 25 • 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? 26 • 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? 27 • 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. RxJava vs Coroutines Most Devs use RxJava for easy Threading

    -Chris Banes (https://www.youtube.com/watch?v=EOjq4OIWKqM) 28
  15. End up only using Single, Maybe & Completeable -Chris Banes

    (https://www.youtube.com/watch?v=EOjq4OIWKqM 29
  16. Suspend Functions 36 • Marked with suspend modifier • Suspend

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

    the execution of the code without blocking the current thread of execution
  18. Coroutine Builder 40 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
  19. Job 46 Job • Cancelable thing • Has a life-cycle

    • Destroys when its complete Deferred • Implement Job • Light-weight non-blocking future • await()to wait the result
  20. Coroutine Dispatcher 48 • 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)
  21. Coroutine Dispatcher 49 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
  22. Coroutine Dispatcher 50 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
  23. Coroutine Dispatcher 51 Notes : • Launch and async accept

    optional dispatcher • Launch(Dispatchers.Default) { … } uses the same dispatcher as GlobalScope.launch { … }
  24. 55 Coroutine Dispatcher The second println operation prints kotlinx.coroutines.DefaultExecutor because

    delay suspends the coroutine using the default scheduler. https://bit.ly/2ZvrHUi
  25. Structured Concurrencies 57 • Coroutines are light weight, How about

    run all business logic/code using GlobalScope.launch?
  26. 58

  27. Structured Concurrencies 59 • 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?
  28. Structured Concurrencies 68 Well don’t you think it’s too much

    to add every coroutine and cancel all manually? Here comes...
  29. Coroutine Scope 76 • 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.
  30. 78

  31. Jadi apa saja manfaat Coroutines? 80 • 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
  32. Resources Link 81 - 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 - 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 )