kevinherron
08/09/2019, 5:09 PMjw
08/09/2019, 5:11 PMval foo = suspend { delay(100); println("Hi") }
runBlocking {
foo()
}
kevinherron
08/09/2019, 5:25 PMBig Chungus
08/09/2019, 5:25 PMkevinherron
08/09/2019, 5:25 PMsuspend fun <T, K, R> groupMapCollateSuspending(
items: List<T>,
grouper: (T) -> K,
mappers: (K) -> suspend (List<T>) -> List<R>
): List<R> {
val pending = items.map { Pending<T, R>(it) }
val grouped: Map<K, List<Pending<T, R>>> =
pending.groupBy { grouper(it.item) }
val jobs = mutableListOf<Job>()
grouped.forEach { (key, pendingForKey) ->
coroutineScope {
jobs += this.launch {
val itemsForKey = pendingForKey.map { it.item }
val results = mappers(key)(itemsForKey)
for (i in 0 until pendingForKey.size) {
pendingForKey[i].result = results[i]
}
}
}
}
jobs.forEach { it.join() }
return pending.map { it.result!! }
}
private class Pending<T, R>(internal val item: T) {
@Volatile
internal var result: R? = null
}
Big Chungus
08/09/2019, 5:26 PMkevinherron
08/09/2019, 5:26 PMgroupMapCollateSuspending(
readValueIds,
{ id -> id.key() },
{ key ->
{ ids: List<ReadValueId> ->
when (key) {
DeviceValueRead -> readDeviceValues(ids)
DeviceNonValueRead -> readDeviceNonValues(ids)
LocalAttributeRead -> readLocalAttributes(ids)
}
}
}
)
Big Chungus
08/09/2019, 5:26 PMkevinherron
08/09/2019, 5:26 PMserebit
08/09/2019, 5:30 PMkevinherron
08/09/2019, 5:33 PM