LiveStreamAsync - asynchronous stream assign in LiveView

Streaming results in LiveView allows working with large collections without keeping them on the server. This functionality is not available out of the box yet.

live_stream_async library provides a useful macro stream_async() that autogenerates the boilerplate for asynchronous stream assign in your LiveView

Usage

  use LiveStreamAsync

  def mount(%{"location" => location}, _, socket) do
    {:ok,
     socket
     |> stream_async(:hotels, fn -> Hotels.fetch!(location) end)
    }
  end

Rendering:

def render(assigns) do
~H"""
<.async_result :let={stream_key} assign={@hotels}>
  <:loading>Loading hotels...</:loading>
  <:failed :let={_failure}>There was an error loading the hotels. Please try again later.</:failed>
      <ul id="hotels_stream" phx-update="stream">
        <li :for={{id, hotel} <- @streams[stream_key]} id={id}>
          <%= hotel.name %>
        </li>
      </ul>
</.async_result>
"""
end
1 Like