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

kevinherron

08/09/2019, 5:09 PM
or suspending lambdas i guess
j

jw

08/09/2019, 5:11 PM
Copy code
val foo = suspend { delay(100); println("Hi") }
runBlocking {
  foo()
}
k

kevinherron

08/09/2019, 5:25 PM
can it take a parameter somehow?
b

Big Chungus

08/09/2019, 5:25 PM
You can use suspend lamda like any other lamda
k

kevinherron

08/09/2019, 5:25 PM
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

Big Chungus

08/09/2019, 5:26 PM
Val x = suspend String.(Int, Any) -> Long
k

kevinherron

08/09/2019, 5:26 PM
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

Big Chungus

08/09/2019, 5:26 PM
That's valid
k

kevinherron

08/09/2019, 5:26 PM
the IDE does not complain, but the compiler does
s

serebit

08/09/2019, 5:30 PM
Try enabling new type inference
k

kevinherron

08/09/2019, 5:33 PM
yeah, new type inference makes it work
ok, good enough for me
3 Views