import { ConstructorType, DestroyableType, DestroyContainer, Message, MessageType, } from "silentium"; /** * Depending on the $condition message, * creates a new left or right message. * When condition changes, old messages are destroyed * and new ones are created. */ export function BranchLazy( $condition: MessageType, $left: ConstructorType<[], MessageType>, $right?: ConstructorType<[], MessageType>, ): MessageType & DestroyableType { return Message(function BranchLazyImpl(r) { const dc = DestroyContainer(); const destructor = () => { dc.destroy(); }; $condition.then(function branchLazySub(v) { destructor(); let instance: MessageType | undefined; if (v) { instance = $left(); } else if ($right) { instance = $right(); } if (instance !== undefined) { instance.then(r); dc.add(instance); } }); return destructor; }); }