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

Coroutines I : The Subtle Bliss Of Coroutines

Coroutines I : The Subtle Bliss Of Coroutines

This is the first talk in a four edition series that focuses on becoming good with coroutines. This talk is a gentle introduction to coroutines and what problem they're trying to solve and why. It also shows the audience how to run coroutines.

Brian Odhiambo

June 15, 2023
Tweet

More Decks by Brian Odhiambo

Other Decks in Programming

Transcript

  1. 02 Design Centric Engineer Brian Odhiambo Dishwasher @ Baobab Circle

    Co-organizer @ KotlinKenya Maintaining @ KotlinBits Yeah am all about that UI/UX & Kotlin
  2. HOW How to use coroutines WHY Why use coroutines The

    World of Concurrency 03 WHAT What are coroutines synchronous! asynchronous! structured!
  3. Works concurrently with the rest of the code Similar to

    threads but lightweight Is not tied to any thread Expressed in a structured way What are coroutines? An instance of suspendable computation
  4. An Example Coroutines marked with suspend import kotlinx.coroutines.* suspend fun

    main() { println("Starting Work") doWork() } suspend fun doWork(){ delay(1000) println("Finished Work") } Starting Work Finished Work 06
  5. Prevents the callback hell problem Easily maintainable & scalable Gives

    you more control of how you handle jobs Less resource intensive than JVM threads (2mb) Why Coroutines ? sendRequest( onSuccess = { sendAnotherRequest( onSuccess = {...}, onFailure = {...}, ) }, onFailure = {...} )
  6. Why Coroutines ? FROM : sendRequest( onSuccess = { sendAnotherRequest(

    onSuccess = {...}, onFailure = {...}, ) }, onFailure = {...} ) TO : val result = sendRequest() if(response != null){ val result = sendAnotherResponse() ... } ...
  7. Example custom coroutine marked with suspend import kotlinx.coroutines.* fun main()

    { println("Starting Work") GlobalScope.launch { doWork() } Thread.sleep(2000) } suspend fun doWork(){ delay(1000) println("Finished Work") } Starting Work Finished Work 11
  8. Example II custom coroutine marked with suspend import kotlinx.coroutines.* fun

    main() { println("Starting Work | ${Thread.currentThread().name}") GlobalScope.launch { doWork("1") } CoroutineScope(Dispatchers.IO).launch { doWork("2") } Thread.sleep(3000) } suspend fun doWork(name: String){ delay(1000) println("Finished Work $name | ${Thread.currentThread().name}") } Starting Work | main Finished Work 1 | DefaultDispatcher-worker-2 @coroutine#1 Finished Work 2 | DefaultDispatcher-worker-2 @coroutine#2 12
  9. Jobs What are Jobs and what is their lifecycle... Builders

    How can you use builders to create coroutines Advanced Coroutine Concepts 14 Contexts What are contexts and what is context switching and so much more!
  10. KotlinBits 😎 A fun and easy way to learn Kotlin

    in small bits and pieces. React, Comment & Share kotlinbits.vercel.app