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

dharrigan

08/11/2019, 12:15 PM
Copy code
fun doSomething() = GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    writeIntoTable1()
    writeIntoTable2()
    writeIntoTable3()
}

suspend fun writeIntoTable1() {...}
suspend fun writeIntoTable2() {...}
suspend fun writeIntoTable3() {...}
g

gildor

08/11/2019, 2:29 PM
okay, there are a few layers in this question 1. First option will run writes in parallel, second sequentially, choose what is suits your use case better 2. Implementing doSomething in a such way is a very bad approach, especially with GlobalScope. Instead, I would just make doSomething suspendable and use
coroutineScope {}
to group writes, so client could launch this suscpend function in own scope using launch, or just call suspend function (which is even better) 3. To make parallel version of this code less awkward I would use something like:
Copy code
listOf(::writeIntoTable1, ::writeIntoTable2, ::writeIntoTable3).forEach { launch ( it() } }
Or any other way to group operations and do not copy paste invocation strategy 4. i see that you use IO dispatcher which looks suspicious in this case, because you call suspend function which itself never should block, so if write is blocking, just move this IO dispatcher to those functions or make them blocking explicitly, remove suspend modifier and add Blocking suffix
d

dharrigan

08/11/2019, 3:51 PM
thanks for the great tips! 🙂
d

Dico

08/11/2019, 10:33 PM
What is Blocking suffix?
@gildor
g

gildor

08/12/2019, 3:50 AM
I mean if
writeIntoTableN
is blocking better to remove suspend modifier which is probably useless and rather confusing for blocking function and rename it to writeIntoTableBlocking, so it will be clear that function is blocking and should be called from corresponding context
d

Dico

08/12/2019, 9:38 AM
Oh name suffix of course, I'm an idiot
I thought you meant there's some kind of unified marker thing
5 Views