DEV Community

Discussion on: Explain coroutines like I'm five

Collapse
 
idanarye profile image
Idan Arye • Edited

I think your explanation is missing the main appeal of async - that you don't need to block on IO.

To build on your story, I'd put it something like this:

  • You start watching the cartoon, but it's the intro.
  • Instead of watching the intro you switch to the game and enter the online lobby - but it needs 3 players and only you and your sister are in it.
  • Instead of waiting for another player to join you switch to your homework, and answer the first question.
  • The second question has a link to a YouTube video you need to watch. You open it - and it starts loading.
  • Instead of waiting for it to load, you switch back to the cartoon. The intro is over, so you can watch.
  • Now there are commercials - but meanwhile a third player has joined so you switch to the game

And so on...

The idea is that you don't just switch the tasks really fast to make it look like you are doing everything at once. You utilize the time you are waiting for something to happen(IO) to do other things that do require your direct attention.

Collapse
 
tiffany profile image
tiff

This. This makes so much sense. Really great explanation.

Collapse
 
bgadrian profile image
Adrian B.G.

True, your completion explain how they should be used, in a correct way.

Collapse
 
thibmaek profile image
Thibault Maekelbergh

Thank you, this was clear enough to grasp it a bit better. I thought coroutines were a specific pattern for async operations though, but from above comments, it seems like they're roughly the same thing.

Thread Thread
 
idanarye profile image
Idan Arye

No - your were right at first. Coroutines are one way to do async - there are other ways. There are also other uses for coroutines. I've written a detailed reply to the main post.

Collapse
 
berserker1 profile image
Aaryan Bhagat

So couroutine is code based context switching, where you write the code and you write the code for context switching (where a function will stop and pass the execution to the caller).