global-bus.ts 882 B

12345678910111213141516171819202122232425262728293031
  1. import { GlobalBus, type GlobalEvent } from "@/bus/global"
  2. import { Cause, Effect } from "effect"
  3. export function waitGlobalBusEvent(input: {
  4. timeout?: number
  5. message?: string
  6. predicate: (event: GlobalEvent) => boolean
  7. }) {
  8. return Effect.callback<GlobalEvent, unknown>((resume) => {
  9. const cleanup = () => GlobalBus.off("event", handler)
  10. const handler = (event: GlobalEvent) => {
  11. try {
  12. if (!input.predicate(event)) return
  13. cleanup()
  14. resume(Effect.succeed(event))
  15. } catch (error) {
  16. cleanup()
  17. resume(Effect.fail(error))
  18. }
  19. }
  20. GlobalBus.on("event", handler)
  21. return Effect.sync(cleanup)
  22. }).pipe(
  23. Effect.timeout(input.timeout ?? 10_000),
  24. Effect.mapError((error) =>
  25. Cause.isTimeoutError(error) ? new Error(input.message ?? "timed out waiting for global bus event") : error,
  26. ),
  27. )
  28. }