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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With