or suspending lambdas i guess
# coroutines
k
or suspending lambdas i guess
j
Copy code
val foo = suspend { delay(100); println("Hi") }
runBlocking {
  foo()
}
k
can it take a parameter somehow?
b
You can use suspend lamda like any other lamda
k
I should better qualify this, hang on
given:
Copy code
suspend 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
}
b
Val x = suspend String.(Int, Any) -> Long
k
I cannot call it like this:
Copy code
groupMapCollateSuspending(
    readValueIds,
    { id -> id.key() },
    { key ->
        { ids: List<ReadValueId> ->
            when (key) {
                DeviceValueRead -> readDeviceValues(ids)
                DeviceNonValueRead -> readDeviceNonValues(ids)
                LocalAttributeRead -> readLocalAttributes(ids)
            }
        }
    }
)
b
That's valid
k
the IDE does not complain, but the compiler does
s
Try enabling new type inference
k
yeah, new type inference makes it work
ok, good enough for me