Skuld.Coroutine.PageMachine (skuld_concurrency v0.36.0)

View Source

Synchronous page-machine for LiveView integration.

Wraps Skuld.Coroutine with a callback-based API. Callbacks are provided once at mount; subsequent resumes are one-liners. The fiber is stored in socket.assigns.pm automatically — callbacks never see it.

Example

alias Skuld.Coroutine.PageMachine

# mount — one-time setup
PageMachine.run(MyApp.CheckoutFlow.flow(cart), socket,
  on_yield: fn step, socket -> {:noreply, assign(socket, step: step)} end,
  on_complete: fn {:ok, order}, socket -> {:noreply, assign(socket, order: order, step: :done)} end,
  on_error: fn reason, socket -> {:noreply, put_flash(socket, :error, inspect(reason))} end,
  on_cancel: fn reason, socket -> {:noreply, push_navigate(socket, to: ~p"/cart")} end
)

# handle_event — one-liner
def handle_event("submit", %{"value" => v}, socket),
  do: PageMachine.run(socket.assigns.pm, {:ok, v}, socket)

For cross-process use, see Skuld.AsyncCoroutine.AsyncPageMachine.

Summary

Types

t()

A page machine carrying the current fiber and callback functions. Stored in socket.assigns.pm between calls.

Functions

Cancel a page machine. Dispatches through on_cancel if available.

Start a page machine with callbacks. Runs the first step of the computation and dispatches the result through the appropriate callback.

Types

t()

@type t() :: %Skuld.Coroutine.PageMachine{
  fiber: Skuld.Coroutine.ExternalSuspended.t(),
  on_cancel: (term(), map() -> term()) | nil,
  on_complete: (term(), map() -> term()) | nil,
  on_error: (term(), map() -> term()) | nil,
  on_yield: (term(), map() -> term())
}

A page machine carrying the current fiber and callback functions. Stored in socket.assigns.pm between calls.

Functions

cancel(pm, reason \\ :cancelled)

Cancel a page machine. Dispatches through on_cancel if available.

Returns {:noreply, socket}.

run(computation, socket, callbacks)

Start a page machine with callbacks. Runs the first step of the computation and dispatches the result through the appropriate callback.

Callbacks:

  • :on_yield (required) — (value, socket) -> {:noreply, socket}
  • :on_complete(result, socket) -> {:noreply, socket}
  • :on_error(error, socket) -> {:noreply, socket}
  • :on_cancel(reason, socket) -> {:noreply, socket}

Returns {:noreply, socket}. Stores the page machine in socket.assigns.pm for subsequent run/3 calls.