cloudstream/app/src/main/java/com/lagradost/cloudstream3/ParCollections.kt

68 lines
2 KiB
Kotlin
Raw Normal View History

2021-05-15 23:37:42 +00:00
package com.lagradost.cloudstream3
2022-01-30 01:50:49 +00:00
import com.lagradost.cloudstream3.mvvm.logError
2021-05-20 15:22:28 +00:00
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
2021-05-15 23:37:42 +00:00
//https://stackoverflow.com/questions/34697828/parallel-operations-on-kotlin-collections
/*
2021-05-15 23:37:42 +00:00
fun <T, R> Iterable<T>.pmap(
numThreads: Int = maxOf(Runtime.getRuntime().availableProcessors() - 2, 1),
exec: ExecutorService = Executors.newFixedThreadPool(numThreads),
transform: (T) -> R,
): List<R> {
// default size is just an inlined version of kotlin.collections.collectionSizeOrDefault
val defaultSize = if (this is Collection<*>) this.size else 10
val destination = Collections.synchronizedList(ArrayList<R>(defaultSize))
for (item in this) {
exec.submit { destination.add(transform(item)) }
}
exec.shutdown()
exec.awaitTermination(1, TimeUnit.DAYS)
return ArrayList<R>(destination)
}*/
2021-05-20 15:22:28 +00:00
2022-04-08 19:38:19 +00:00
fun <K, V, R> Map<out K, V>.apmap(f: suspend (Map.Entry<K, V>) -> R): List<R> = runBlocking {
map { async { f(it) } }.map { it.await() }
}
2022-01-29 18:37:23 +00:00
fun <A, B> List<A>.apmap(f: suspend (A) -> B): List<B> = runBlocking {
2021-05-20 15:22:28 +00:00
map { async { f(it) } }.map { it.await() }
2022-01-29 18:37:23 +00:00
}
2022-05-02 21:32:28 +00:00
fun <A, B> List<A>.apmapIndexed(f: suspend (index: Int, A) -> B): List<B> = runBlocking {
mapIndexed { index, a -> async { f(index, a) } }.map { it.await() }
}
2022-01-29 18:37:23 +00:00
// run code in parallel
/*fun <R> argpmap(
2022-01-29 18:37:23 +00:00
vararg transforms: () -> R,
numThreads: Int = maxOf(Runtime.getRuntime().availableProcessors() - 2, 1),
exec: ExecutorService = Executors.newFixedThreadPool(numThreads)
) {
for (item in transforms) {
exec.submit { item.invoke() }
}
exec.shutdown()
exec.awaitTermination(1, TimeUnit.DAYS)
}*/
2022-01-29 18:37:23 +00:00
2022-01-30 01:50:49 +00:00
// built in try catch
fun <R> argamap(
vararg transforms: suspend () -> R,
) = runBlocking {
2022-01-30 01:50:49 +00:00
transforms.map {
async {
try {
it.invoke()
} catch (e: Exception) {
logError(e)
}
}
}.map { it.await() }
}