Hi, I still doesn't understand the basics of corou...
# coroutines
a
Hi, I still doesn't understand the basics of coroutines, like how to properly create some and launch them in a simple project, what are the dispatchers, how to launch multiple time a suspending function to optimise a big normal function etc Can someone explain me this examples please ?
g
https://github.com/gklijs/Kotlin-coroutines-demo might help. Kind of struggling right now to explain coroutines nicely. Basically it's an abstraction on top of threads to make it easier to run things in parallel.
j
Have you already read through the official documentation on coroutines? It would be nice to understand what you already know, so we can fill in the blanks.
how to properly create some and launch them in a simple project
I think the less obvious thing to understand is how structured concurrency works. Examples of "simple projects" work fine with a
suspend fun main
or a
runBlocking
but in real life (applications and servers where you don't use the main method directly), you have to be comfortable with how to use coroutine scopes. So to answer your first question, creating a coroutine is as simple as using a coroutine builder (
launch
,
async
etc.). These can be called from non suspending contexts (like a regular function), and their body can call suspend functions. That's how you bridge the 2 worlds together. The hard part is giving those functions the correct
CoroutineScope
.
What are dispatchers?
Dispatchers are responsible for organizing the execution of coroutines. You can think of them as an abstraction over a thread pool and a task queue (like java's executor service, if that's any help). So in essence choosing a dispatcher is about choosing a thread pool that will run your coroutines. It's important for controlling what runs on UI thread in Android apps, or what runs on IO-dedicated threads etc. I'm not sure I understand your last question. Are you talking about launching pieces of a big function concurrently using coroutines so it finishes faster?
❤️ 1
v
There are so many very good and easy to understand tutorial available to read, here are few of them you can refer : official : 1.

https://www.youtube.com/watch?v=_hfBv0a09Jc&

2.

https://www.youtube.com/watch?v=a3agLJQ6vt8

other one

https://www.youtube.com/watch?v=C38lG2wraoo&list=PLlxmoA0rQ-Lzyprk1wxs4CT15hOqvW0oC