Really Stream Into Your LiveView Streams
Almost every Elixir project I've worked on used Phoenix LiveView streams to display an infinite list of data. Usually, the LiveView process queries the database directly and applies pagination. Other times, some internal interface calls the database, but, again, the LiveView or, God forbid, a live component is responsible for passing the correct pagination options.
Streaming interface
At the business-logic boundary, we can imagine the following function for streaming blog posts.
import Ecto.Query
def stream_posts(batch_size) do
Stream.resource(
fn -> %{page: 0, size: batch_size} end,
fn state ->
posts =
list_posts_query()
|> offset(state.page * state.size)
|> limit(state.size)
|> Repo.all()
case posts do
[] -> {:halt, state}
_ -> {posts, %{state | page: state.page + 1}}
end
end,
fn _ -> :ok end
)
end
The stream_posts/1 function is intentionally simplistic. In a
production codebase you'd most probably want to use the seek method
for pagination because it's much faster for use cases like this. The
data might not come from your application's database at all, or only
partially. Calls to external services impose more elaborate error
handling. Enough excuses already! The user interface is the
interesting part anyway.
Long live the caller
For our purposes, the caller of our streaming interface is a LiveView
process. In the mount/3 function we need to call stream_posts/1,
take the first batch of posts, and stream them to the client.
@query_size 10
@client_size 10
def mount(_, _, socket) do
# `posts_list` is a nested list and needs unwrapping later.
{posts_list, posts_stream} =
stream_posts(@query_size)
|> Stream.chunk_every(@client_size)
|> StreamSplit.take_and_drop(1)
socket =
socket
|> assign(:posts_stream, posts_stream)
|> stream(:posts, List.first(posts_list, []))
{:ok, socket}
end
The query size and the client size are equal, but they don't have to be. A query size that is double the client size means that every second batch is prefetched and already in memory when needed.
You might be wondering about StreamSplit.take_and_drop/2. It enables
us to take the first n elements of the stream while also returning
the rest of the stream. When the stream runs out, the taken list is
empty and streaming an empty list is a no-op.
Rather than tying the batch request event name to a particular
LiveView version or a client hook, let's assume the process receives a
"load-more" event. Processing such an event is trivial now. It
consists of taking the next batch off the stream, streaming it to the
client, and storing the rest.
def handle_event("load-more", _, socket) do
{posts_list, posts_stream} =
StreamSplit.take_and_drop(socket.assigns.posts_stream, 1)
socket =
socket
|> assign(:posts_stream, posts_stream)
|> stream(:posts, List.first(posts_list, []))
{:noreply, socket}
end
As you can see, there is no tracking of the last loaded batch, the
query size, or the client size. The stream is handled exactly as it is
in mount/3.
Parting thoughts
This technique for managing client-facing streams of data completely decouples the data querying from the presentation logic. The LiveView process shouldn't be, and isn't, concerned with any Ecto repository, the pagination method, or whether the data comes from an external service. The technique is also very much to my taste because it's functional. The stream returned by the business logic is treated as a value, a purpose-built data structure, not scattered values assembled as arguments when needed.