intercept

inline fun <E : Effect<*>, A> Program<A>.intercept(noinline rule: suspend ProgramScope.(effect: E, proceed: suspend ProgramScope.() -> Any?) -> Any?): Program<A>(source)

Middleware: observe an effect without consuming it. proceed() re-emits the effect to the handler downstream and returns its response, so the rule decides where the effect executes and may inspect, rewrite or replace the result; a rule that answers without calling proceed() consumes the effect. Effects the rule performs itself are seen only by the handlers applied after this one, so a middleware that logs needs the log handler downstream of it.

Each intercepted effect is handled twice, and the rule's coroutine is parked in between, which costs a few times a plain handle; keep it off hot paths. The cheaper form, and the one that works under a multi-shot handler, is an interpret rule that re-emits the effect and continues from a flatMap: interpret<NonDet<*>, A> { op, resume -> perform(op).flatMap { resume(it) } }. Under a multi-shot handler an intercept on the same effect fails, because proceed() suspends the one-shot rule block and the downstream handler resumes it once per option; an intercept on an unrelated effect is fine. Applied lazily, when the program is run.