F
F
foonfyrick2021-01-17 14:28:03
Kotlin
foonfyrick, 2021-01-17 14:28:03

CoroutineScope(Dispatchers.Main).launch{} vs CoroutineScope(Dispatchers.Main).launch(DispathersMain){}?

1. I don’t quite understand why the name of the coroutine should be specified in the constructor, because then you can’t specify the execution flow for it, you can only at launch, and the name of the coroutine is shown simply in the logs.

val scope1 = CoroutineScope(CoroutineName("MyCoroutine"))
//либо так
           scope1.launch{}
//либо так
           scope1.launch(Dispatchers.Main){}

2. What is the difference if I specify Dispatchers.Main in the coroutine constructor or in the launcher constructor?
val scope2 = CoroutineScope(Dispatchers.Main)
//либо так
           scope2.launch{}
//либо так
           scope2.launch(Dispatchers.Main){}

3. What is the difference between CoroutineScope(Dispatchers.Main).launch{} vs CoroutineScope(Dispatchers.Main).launch(DispathersMain){}?
I read that the context specified in the CoroutineScope constructor is the place of execution in the corresponding thread (in the main thread or in a new one), and launch is the launch of the coroutine itself, in which you can add a bunch of launches, for each launch you can specify the place of execution in the constructor, but, why then specify the execution location of the CoroutineScope? I'm confused.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2021-01-18
@foonfyrick

1) the name of the coroutine is needed only for debugging
2) there is no launch constructor, it's just a function on the CoroutineScope. There is no difference between these examples. You can transfer a dispatcher if you want to launch to another dispatcher.
3) this is like a repetition of the second question. I'll expand a bit. If a dispatcher (D) is passed to CoroutineScope, then all launches without additional dispatchers will occur on dispatcher D. And if not passed, then all such launches will occur on Dispatchers.Default, that is, for android - on a dispatcher that has several threads, and on which you can perform heavy calculations.
Launches to which a dispatcher is passed will be executed on that dispatcher.
Something like this. This is actually a complex and confusing topic. Behind the external simplicity lies a very complex machinery. You've covered some pretty simple stuff so far.

F
foonfyrick, 2021-01-17
@foonfyrick

I found the answer to the first question, the context can be combined with the name through +

val scope1 = CoroutineScope(CoroutineName("MyCoroutine")+Dispatchers.IO)

two other sub-questions are still unresolved

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question