Tower Guidev2
03/17/2022, 10:56 AMTower Guidev2
03/17/2022, 10:57 AMprivate fun something(things: List<Thing>): List<OtherThing> {
val otherThings = mutableListOf<OtherThing>()
runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
things.map {
async {
val whatEver = somethingElse(it)
if (whatEver) otherThings.add(process(it))
}
}.awaitAll()
}
return otherThings.take(someAmount.toInt())
}
fun process(thing: Thing): OtherThing {
return thing.copy(data = thing.data.replace(Regex(NON_LETTER_PATTERN), ""))
}
Tower Guidev2
03/17/2022, 11:01 AMrunBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {}
to runBlocking {}
i never see assert failuresTower Guidev2
03/17/2022, 11:03 AMxxx.map ( async {} )
has a subtle bug
however i cannot find that now
if i shouldnt be using runBlocking in production code
what are my alternatives?Sam
03/17/2022, 11:03 AMotherThings
listSam
03/17/2022, 11:04 AM<http://Dispatchers.IO|Dispatchers.IO>
has multiple threads so the async tasks could run in parallel, whereas with just runBlocking
it would run in a single threaded event loopTower Guidev2
03/17/2022, 11:06 AM<http://Dispatchers.IO|Dispatchers.IO>.limitedParallelism(1)
Tower Guidev2
03/17/2022, 11:06 AMrunBlocking
Sam
03/17/2022, 1:12 PMrunBlocking
is most important if this code is already running inside a coroutine. In that case, you should make something
a suspend function, and replace runBlocking
with coroutineScope { ... }
.Sam
03/17/2022, 1:12 PMrunBlocking
may be an okay choice