Ayfri
11/20/2021, 8:37 AMGerard Klijs
11/20/2021, 9:18 AMGerard Klijs
11/20/2021, 9:49 AMJoffrey
11/20/2021, 10:01 AMhow to properly create some and launch them in a simple projectI 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?
Vaibhav Tripathi
11/20/2021, 1:43 PM