A gentle introduction to Kotlin Coroutines

A gentle introduction to Kotlin Coroutines

903d5bc2f50236c69d390ba4d5ff94a8?s=128

Arturo Mejia

March 25, 2019
Tweet

Transcript

  1. A gentle introduction to Kotlin Coroutines Arturo Mejia Twitter: @ArturoMejia481

    ArturoMejiaMarmol.com
  2. None
  3. Alternatives @ArturoMejia481 Threads Callbacks RX (Reactive extensions) Futures Promises

  4. Threads @ArturoMejia481 Expensive, not easy to use. IOS deprecate threads.

    DispatchQueue
  5. Callbacks @ArturoMejia481 Don't call me, I'll call you!

  6. Callbacks @ArturoMejia481 Callback Hell

  7. Callbacks @ArturoMejia481 Callback Hell a.k.a Tilted Christmas Tree.

  8. Callbacks @ArturoMejia481 Difficult error handling.

  9. Promises and Futures @ArturoMejia481

  10. Reactive Extensions @ArturoMejia481 You have to change the way that

    you approach a problem. Operators RX Schedulers Streams
  11. @ArturoMejia481 Reactive Extensions

  12. @ArturoMejia481 Kotlin Coroutines Do async work the same way, exceptions,

    loops, etc…
  13. @ArturoMejia481 Kotlin Coroutines Clear differences between suspend functions

  14. @ArturoMejia481 Kotlin Coroutines Same function signature

  15. Coroutines = Lightweight @ArturoMejia481 Threads Coroutines

  16. @ArturoMejia481 Kotlin Coroutines

  17. Goal @ArturoMejia481 Suspend Dispatchers Coroutine Builders Launch Async/await

  18. Suspend @ArturoMejia481 A key word to indicate the compiler that

    a function can be suspended.
  19. Suspend @ArturoMejia481 A suspend function should be called from a

    coroutine or another suspend function.
  20. Suspend @ArturoMejia481 The Kotlin compiler transforms the function to a

    callback model and uses state machines to know when a function should be suspended or resume.
  21. @ArturoMejia481 Coroutine ≈ Threads

  22. Let’s get our hands dirty! @ArturoMejia481

  23. Launch @ArturoMejia481 Launch is when we want to fire and

    forget.
  24. Async @ArturoMejia481 Async is when we want to run something,

    then await the result.
  25. Dispatchers @ArturoMejia481 DEFAULT (Computational) Uses the # cores of the

    CPU, not good for computations like I/O, network, disk, etc. IO designed for doing blocking I/O operations, max #64 thread, share the pool with DEFAULT. MAIN designed to operate UI objects. Indicate in which thread pool a coroutine should run
  26. Interoperate @ArturoMejia481 kotlinx-coroutines-rx2: Utilities for Rx. kotlinx-coroutines-jdk8: Integration with JDK8

    CompletableFuture (Android API level 24). kotlinx-coroutines-android: Designed to operate UI objects.
  27. “With a great power, comes responsibility” @ArturoMejia481 Spiderman

  28. Questions? @ArturoMejia481

  29. Thanks! Twitter: @ArturoMejia481 ArturoMejiaMarmol.com Android Tutorials RayWenderLich.com/u/amejia481