Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are use cases for coroutines?

The concept of a coroutine sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use cases for coroutines, where the coroutine implementation is more elegant, simpler or more efficient than other methods?

like image 907
Mnementh Avatar asked Nov 19 '08 23:11

Mnementh


People also ask

What can coroutines be used for?

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.

When should you use coroutines?

It's worth considering using a Coroutine whenever you want to create an action that needs to pause, perform a series of steps in sequence or if you want to run a task that you know will take longer than a single frame.

What problems do coroutines solve?

Coroutines are useful to get rid of callbacks. Assume that you have a function that must perform some expensive computation: solveAllProblems . This function calls a callback that receives the result of the computation and performs what is needed (e.g., it saves the result in a database).

Are coroutines better than threads in all situations?

So, it's not a “magical” technology, that is better than threads, but just a different concept of concurrency used in your applications. Unlike threads, coroutines are not bound to any particular thread. A coroutine can start executing in one thread, suspend execution, and resume on a different thread.


1 Answers

One use case is a web server that has multiple simultaneous connections, with a requirement to schedule reading and writing in parallel with all of them.

This can be implemented using coroutines. Each connection is a coroutine that reads/writes some amount of data, then yields control to the scheduler. The scheduler passes to the next coroutine (which does the same thing), cycling through all the connections.

like image 87
Ali Afshar Avatar answered Sep 30 '22 22:09

Ali Afshar