A proof-of-concept demonstrating just how easy it is to create real-time applications with LiveView.
Just mix setup followed by iex -S mix phx.server. Visit localhost:4000 and watch the magic.
Inspired by https://firesky.tv
The magic code is:
# lib/firesky_web/live/home_live.ex
def handle_info({:frame, json_map}, socket) do
id = json_map["commit"]["cid"]
json =
json_map
|> Jason.encode!()
|> Jason.Formatter.pretty_print()
socket = stream_insert(socket, :frames, {id, json}, limit: -10, at: 0)
{:noreply, socket}
endand
def handle_info({:gun_ws, _conn_pid, _stream_ref, frame}, state) do
{:text, raw_json} = frame
json_map = Jason.decode!(raw_json)
Phoenix.PubSub.broadcast(Firesky.PubSub, "firehose", {:frame, json_map})
{:noreply, state}
endand finally, to display:
<div id="feed" phx-update="stream" class="flex flex-col gap-y-4">
<div :for={{id, {_id, frame}} <- @streams.frames} id={id}>
{frame}
</div>
</div>That's it. Seriously.
Screen.Recording.2024-12-13.at.9.33.13.PM.mov
(I'd make it longer, but there's a 10MB file limit for video attachments)