Created
December 20, 2018 08:02
-
-
Save WaffleLapkin/7a6f6bc8b3f8f26b607a40a8717714e1 to your computer and use it in GitHub Desktop.
Пытаюсь ловить ошибки в фильтрах...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Filter<T /*: ITEvent */> { | |
abstract suspend fun test(value: T): Boolean | |
} | |
class TrueFilter<T: ITEvent>(val sleep: Int, val num: Int, val throwable: Throwable? = null): Filter<T>() { | |
override suspend fun test(value: T): Boolean { | |
println("Enter $num filter, sleeping for $sleep seconds") | |
delay(sleep.seconds.inMilliseconds.longValue) | |
println("Success $num filter, returning `true`") | |
throw throwable ?: return true | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Handler<T /*: ITEvent */>( | |
val filters: Array<out Filter<T>>, | |
val func: suspend (T) -> Unit, | |
val name: String? = null, | |
val logger: KLogger? = null // TODO: make it non-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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) = runBlocking<Unit> { | |
val trueHandler = Handler<String>( | |
arrayOf( | |
TrueFilter(1, 0), | |
TrueFilter(3, 1) | |
), | |
{} | |
) | |
if (trueHandler.test("")) println("trueHandler") else println("not trueHander") | |
val eHandler = Handler<String>( | |
arrayOf( | |
TrueFilter(1, 0), | |
TrueFilter(2, 1, Exception("test")), | |
TrueFilter(3, 2) | |
), | |
{} | |
) | |
if (eHandler.test("")) println("eHandler") else println("not eHandler") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment