Skip to content

Instantly share code, notes, and snippets.

@WaffleLapkin
Created December 19, 2018 17:37
Show Gist options
  • Save WaffleLapkin/74d73d82be5b17ff46bd34092ad5e048 to your computer and use it in GitHub Desktop.
Save WaffleLapkin/74d73d82be5b17ff46bd34092ad5e048 to your computer and use it in GitHub Desktop.
data class Handler<T: ITEvent>(
val filters: Array<out Filter<T>>,
val func: suspend (T) -> Unit,
val name: String? = null
) {
/**
* Test all [filters] of this handler
*
* @return true, if all filters passed, else false
*/
suspend fun test(value: T): Boolean = coroutineScope {
val ch = Channel<Boolean>()
launch{
val jobs = mutableListOf<Job>()
filters.forEach {
jobs.add(launch { ch.send(it.test(value)) })
}
jobs.joinAll()
ch.close()
}
for (data in ch) {
if (!data) {
coroutineContext.cancelChildren() // to kill the rest of tasks we don't need
return@coroutineScope false
}
}
return@coroutineScope true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment