A LiveView is a process: let the job tell it when it's done

· Updated

Coming from other MVC frameworks it’s easy to forget that a LiveView is just an Elixir process, like a GenServer. What works for other processes works for a LiveView too: handle_info/2 can receive messages from jobs, webhook handlers, or tasks.

Subscribing to a job’s PubSub topic on mount is the popular pattern, and it’s quite straightforward. But a LiveView can also start its own async tasks and handle their replies.

Task.async/1 sends {ref, result} back to the process that started it:

lib/my_app_web/live/feed_live.ex
defmodule MyAppWeb.FeedLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    socket = assign(socket, articles: [], loading: nil)

    if connected?(socket) do
      {:ok, assign(socket, :loading, Task.async(&MyApp.Feed.fetch_articles/0))}
    else
      {:ok, socket}
    end
  end

  def handle_info({ref, articles}, %{assigns: %{loading: %Task{ref: ref}}} = socket) do
    Process.demonitor(ref, [:flush])
    {:noreply, assign(socket, articles: articles, loading: nil)}
  end

  def render(assigns) do
    ~H"""
    <button phx-click="refresh">Refresh</button>
    <p :if={@loading}>Loading…</p>
    <p :for={article <- @articles}><%= article %></p>
    """
  end
end

Keeping the task in assigns gives the template a loading flag and lets handle_info/2 match the reply by its ref.

The assign is optional. The reply arrives either way, so a button can start a task and forget about it:

def handle_event("refresh", _params, socket) do
  Task.async(&MyApp.Feed.fetch_articles/0)
  {:noreply, socket}
end

def handle_info({ref, articles}, socket) when is_reference(ref) do
  Process.demonitor(ref, [:flush])
  {:noreply, assign(socket, articles: articles)}
end

With raw tasks:

* In @mount@ start the task only when connected. Without the check, @mount@ runs the work twice, and nobody reads the static render's result.
* @Task.async/1@ also monitors the task, so a @{:DOWN, ref, :process, pid, :normal}@ message follows the reply. @Process.demonitor(ref, [:flush])@ drops it. Without that, or a catch-all @handle_info@, the LiveView crashes with @FunctionClauseError@.
* Without the stored @ref@, replies are anonymous. That's fine for one kind of task, but two kinds would land in the same clause, and after a double click the reply that arrives last wins, even if it was started first.
* The task is linked. If it raises, the LiveView goes down with it.

Update 2023-09-22 LiveView 0.20 added start_async/3 and handle_async/3 (plus assign_async/3). They handle the connection check, the reply, the monitor, and a crashing task, and the key names the reply, so there is nothing to store:

def mount(_params, _session, socket) do
  {:ok,
   socket
   |> assign(articles: [], loading: true)
   |> start_async(:articles, &MyApp.Feed.fetch_articles/0)}
end

def handle_event("refresh", _params, socket) do
  {:noreply,
   socket
   |> assign(loading: true)
   |> start_async(:articles, &MyApp.Feed.fetch_articles/0)}
end

def handle_async(:articles, {:ok, articles}, socket) do
  {:noreply, assign(socket, articles: articles, loading: false)}
end

def handle_async(:articles, {:exit, _reason}, socket) do
  {:noreply, socket |> assign(loading: false) |> put_flash(:error, "Couldn't load the feed.")}
end

Both the mount and the click go through the same handle_async/3 clauses.

Use the async helpers for work the page owns and PubSub for events produced elsewhere.

← All notes