https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Slackbot

06/18/2020, 2:41 PM
This message was deleted.
l

louiscad

06/18/2020, 2:45 PM
@allan.conda Wrap with
coroutineScope { ... }
.
a

allan.conda

06/18/2020, 2:48 PM
I tried it, and logged the scope instance. I get StandaloneCoroutine in the calling fun and DispatchedCoroutine in that one. Ah no, I get this from withContext() I get ScopeCoroutine with your suggestion. Is this instance hanging on to the standalone one?
l

louiscad

06/18/2020, 2:50 PM
I don't really understand what you mean, but basically, you need this instead of what you showed:
Copy code
suspend fun someBatchUpload(): List<Int> = coroutineScope {
    listOf(async { 1 }, async { 2 }).awaitAll()
}
Also, keep reading the coroutines docs, that'll help you understand it all.
Since you're doing Android stuff, there's also this page that you'll find useful: https://d.android.com/kotlin/coroutines
a

allan.conda

06/18/2020, 2:58 PM
I don’t really understand what you mean, but basically, you need this instead of what you showed:
Thanks, looks like I’m not making much sense 😄. Actually, I already came to the conclusion that I needed to use coroutineScope exactly like you wrote, because that’s the only one that didn’t throw a warning or error. But I don’t understand how it works and right now I just assume it does what I think it does; I’m not sure yet how to test scoped coroutine lifecycle so I can’t know for sure.
l

louiscad

06/18/2020, 2:59 PM
There's this great talk about structured concurrency:

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

About lifecycles, it's a different thing, but Android docs should be helfup for that matter after you get stuctured concurrency
🙏 1
e

Evan R.

06/19/2020, 5:36 PM
The android developers video on it is also good. I find that it’s very clear and approachable:

https://youtu.be/ZTDXo0-SKuU

👍 1
But at its most basic a coroutineScope is like a standard if statement scope, it’s a code region that doesn’t exit until all the work inside is complete
The reason for this is to allow people to run things in parallel but still be able to handle errors and cancel jobs when errors occur
If an error is thrown in a parallel job within a coroutine scope, by default the sibling parallel jobs are cancelled and the coroutineScope will rethrow the error that wasn’t dealt with
5 Views