Skip to content

How coroutines programming works

Devrath edited this page Dec 30, 2023 · 5 revisions

png (1)

Concept of coroutines

The Idea of coroutines revolves around the idea of

  • suspension points
  • suspendable functions
  • continuations

Let us consider a sample

fun getMovieDetails(userId: String) {
  print("Getting the movie details") // 1
  val movieDetails = sampleMovieService.getMovie(userId) // 2
  print("Getting the movie details") // 3
  print(movieDetails.movieName) // 4
  print("Movie details displayed") // 5
}
  • 1 is executed -> 2 gets suspended -> then 3,4,5 gets executed one after another.
  • So 2 calls a suspending function and waits for it to return before 3,4,5 is executed.
  • Important thing to notice here is that there is no callback and streams.
  • Also 2 once suspended is wrapped in a suspend function and added to the thread pool -> It might execute quickly of its waiting to execute -> further lines are executed -> Until the suspended variable is used which we call await -> if still hasn't executed it suspends the entire program and waits for suspended function to execute
  • Meaning we can do as much as processing in between the call and using the result of that call because the compiler knows about suspending functions and suspending points -> so you can think they are working sequentially and have a clean code. which is extendable and easy to maintain.
  • Since the coroutines are so simple, because of this we can chain them and combine them, unlike other operators.
  • Also an important point to note is that coroutines are not threads, They are low level mechanisms that use thread pools to shuffle work between multiple existing threads -> This allows us to create a million coroutines without memory overhead otherwise if coroutines were threads even in the modern computers would crash.
Clone this wiki locally