Writing a suspend function, and I'm wondering if t...
# coroutines
j
Writing a suspend function, and I'm wondering if there's any meaningful difference between these two options. I think either 1) there isn't, or 2) I've got a gap in my understanding of coroutines. For context:
transformResultRow()
is an expensive operation. Option 1:
Copy code
suspend fun transformData(): List<MyData> {
    val results: List<ResultRow> = queryForData() // queryForData() is a suspend fun querying the db

    return withContext(Dispatchers.Default) {
        results.map { resultRow ->
            async {
                transformResultRow(resultRow) // fun transformResultRow(row: ResultRow): MyData
            }
        }.awaitAll()
    }
}
Option 2: (What's the difference? They both seem to be doing the same thing)
Copy code
suspend fun transformData(): List<MyData> {
    val results: List<ResultRow> = queryForData() // queryForData() is a suspend fun querying the db

    return coroutineScope {
        results.map { resultRow ->
            async(Dispatchers.Default) {
                transformResultRow(resultRow) // fun transformResultRow(row: ResultRow): MyData
            }
        }.awaitAll()
    }
}
It seems that
coroutineScope
is preferred here conventionally.
d
Yeah, the biggest difference is that you're explicitly setting the dispatcher in the first, where the second one will inherit whatever dispatcher was in scope when the transformData() was called.
👍 1
u
Is transformResultRow blocking? Or suspend?