How coroutines programming works - devrath/KotlinAlchemy GitHub Wiki
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
}
- 1is executed ->- 2gets suspended -> then- 3,- 4,- 5gets executed one after another.
- So 2calls a suspending function and waits for it to return before3,4,5is executed.
- Important thing to notice here is that there is no callbackandstreams.
- Also 2once 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 callawait-> 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 functionsandsuspending points-> so you can think they are working sequentially and have a clean code. which is extendable and easy to maintain.
- Since the coroutinesare 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.