AfterHandler.kt

  1. package com.hexagontk.handlers

  2. /**
  3.  * After handlers are executed even if a filter don't call next handler (if after was added before
  4.  * filter).
  5.  *
  6.  * After handlers' filters are always true because they are meant to be evaluated on the **return**.
  7.  * If they are not called in first place, they won't be executed on the return of the next handler.
  8.  * Their filter is evaluated after the `next` call, not before.
  9.  */
  10. class AfterHandler<T : Any>(
  11.     private val afterPredicate: (Context<T>) -> Boolean = { true },
  12.     val callback: (Context<T>) -> Context<T>,
  13. ) : Handler<T> {

  14.     override val predicate: (Context<T>) -> Boolean = { true }

  15.     override fun process(context: Context<T>): Context<T> {
  16.         val next = context.next().with(predicate = afterPredicate)
  17.         return try {
  18.             if (afterPredicate.invoke(next)) callback(next)
  19.             else next
  20.         }
  21.         catch (e: Exception) {
  22.             next.with(exception = e)
  23.         }
  24.     }
  25. }