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

Kotlin Coroutines

pahill
November 26, 2018

Kotlin Coroutines

Explains what a Kotlin coroutine is, explores it's power and gives plenty of examples and resources to get you started!

pahill

November 26, 2018
Tweet

More Decks by pahill

Other Decks in Programming

Transcript

  1. Hello! I AM Pamela A. Hill - Kotlin Principal at

    DVT Twitter: @pamelaahill LinkedIn: www.linkedin.com/in/pamelaahill Blog: www.pamelaahill.com
  2. KotlinConf 2018 keynote • Coroutines promoted to stable • The

    coming year will be the year of coroutines • 4 sessions at the conference devoted to the topic

  3. THREAds • Not cheap, requires context-switching • Not infinite, limited

    by operating system • Not available on all platforms • Prone to bugs, difficult to debug

  4. FUTURES / PROMISES / ETC • Different programming model •

    Requires learning different API each time • Returns a Future or Promise, not the expected data type • Error handling is complicated
 
 

  5. REACTIVE EXTENSIONS (RX) • Observable streams - data considered infinite

    amounts of data that can be observed • Consistent API across platforms • Nicer approach to error handling
 
 
 

  6. COROUTINES • Suspendable computations - a function can suspend its

    computation at some point and resume later on
 • Coroutines are like light-weight threads • Coroutines run on a shared pool of threads, one thread can run many coroutines
 

  7. COROUTINES • Writing non-blocking code is the same as writing

    blocking code - programming model doesn’t change • Consistent across platforms, compiler adapts the code • Doesn’t require learning a new API
 

  8. YOUR FIRST COROUTINE fun main() = runBlocking {
 repeat(100_000) {


    launch {
 delay(10000L)
 print(".")
 }
 }
 }
  9. SUSPENDING FUNCTIONS • Can be paused and resumed at a

    later stage without blocking the thread • Add the suspend modifier to the function signature: 
 suspend fun dockToStation() • Can only be called by other suspending functions or coroutines • The compiler converts suspending function to a function with a Continuation
 

  10. COROUTINE CONTEXT • A key-value map • Job - used

    to determine the state of the operation, cancel the operation • ContinuationInterceptor - intercepts the continuation of the coroutine • CoroutineName - user defined, used for debugging • CoroutineExceptionHandler - handles all exceptions in the coroutine context
 
 

  11. COROUTINE DIsPATCHERS • Ensures that the execution and continuation of

    the coroutines are dispatched on the right threads • Dispatcher.Default - used for CPU intensive tasks • Dispatchers.IO - used for IO intensive operations • Dispatchers.Unconfined - Starts in calling thread, 
 resumes in thread determined by the suspending function • Dispatchers.Main - used for execution in the main thread

  12. COROUTINE BUILDERs • Provides a way to start a coroutine

    • Inherits the context from the scope it was invoked in • Scope controls the lifecycle, should be implemented on components that have a lifecycle of their own • Examples are launch,async,runBlocking

  13. LAUNCH • Creates a fire-and-forget coroutine • Returns a Job,

    which can be used to cancel the coroutine

  14. LAUNCH suspend fun launchSpaceShuttle(){..}
 suspend fun flyToDestination(){...}
 suspend fun dockOnSpaceStation(){...}


    
 val job = launch {
 println("10.9.8.7.6.5.4.3.2.1..ignition")
 launchSpaceShuttle()
 flyToDestination()
 dockOnSpaceStation()
 println("docked")
 }
 println("What were we doing again?") 

  15. runblocking • Creates a coroutine and wait until it is

    done • Often used for unit testing coroutines

  16. runblocking suspend fun launchSpaceShuttle(){..}
 suspend fun flyToDestination(){...}
 suspend fun dockOnSpaceStation(){...}


    
 val job = runBlocking {
 println("10.9.8.7.6.5.4.3.2.1..ignition")
 launchSpaceShuttle()
 flyToDestination()
 dockOnSpaceStation()
 println("docked")
 }
 println("That was amazing!”)
  17. ASYNC • Creates a coroutine that returns a value •

    Returns a Deferred, which can be used to cancel the coroutine • Deferred has an await() function, which will wait until the result is available and then return it • The await() function is also a suspending function

  18. ASYNC suspend fun checkFlightPath(): FlightPath {...}
 suspend fun checkCrewHealth(): CrewHealth

    {...}
 fun reportToMissionControl(flightPath: FlightPath, crewHealth: CrewHealth){...}
 
 val job = launch {
 val flightPath = async {checkFlightPath()}
 val crewHealth = async {checkCrewHealth()}
 reportToMissionControl(flightPath.await(), crewHealth.await())
 }
  19. COROUTINES • KotlinConf 2018, Exploring Coroutines in Kotlin by Venkat

    Subramanium https://youtu.be/jT2gHPQ4Z1Q • Async Operations with Kotlin Coroutines (Part 1 and 2) by Mayowa Adegeye http://bit.ly/2KorsUO • Follow Roman Elizarov on Twitter @relizarov and Medium @elizarov 

  20. NEW KOTLIN RESOURCES • Programming Kotlin by Venkat Subramaniam (currently

    in Beta) http://bit.ly/2R8Mjhw • Kotlin for Java Developers on Coursera by Svetlana Isakova and Andrey Breslav http://bit.ly/2OXeiyR
  21. THANKS! Any questions? Come say hi ✋ You can also

    find me at http://www.pamelaahill.com