Skip to main content

Introduction to Coroutines

·2 mins
  • Continuation is a neat idea: a function executes partially, cedes control and, when it is invoked again, restarts from where it left off last time.
  • Why coroutines?
    • Similar to Go’s goroutines, coroutines are extremely lightweight compared to threads. For e.g., you can easily spin up 100k coroutines but not threads on a regular machine.
    • A key observation is that nowadays most of our code spends time doing network IO. We don’t need computation-level concurrency most of the time.
    • Compared with other languages:
      • C#, Python etc. have async/await to implement concurrency. (If I understood correctly, they are similar to how Java’s concurrency also works: you start something in a separate thread, get a Future or something back and wait for it to complete at the point you want its result.) The default way to use them is to write concurrent code.
      • Kotlin decided to make sequential code the default. If you want concurrent code, you have to make that explicit. Good for whoever is reading the code to understand when concurrency is happening.
  • Kotlin introduced a single modifier: suspend. I think the idea is that such a function suspends - sort of goes to sleep - until the thing it is waiting for is available or done.
    • Coroutines run on top of threads. When a coroutine is suspended, that thread frees up to do other things. Once the coroutine is ready, it will be scheduled on some, possibly different, thread. (So, I think this is the “continuation” part above.)