from Hacker News

Show HN: Topical – Elixir library for synchronising state to web clients

by joefreeman on 9/28/23, 4:58 PM with 0 comments

Hi HN. I've been working on an Elixir library for synchronising state, maintained by the server, to connected web clients. I found this was something I kept implementing for side-projects, so I've extracted it into a library.

It solves a similar problem to Phoenix LiveView, but aimed at a different level of abstraction: rather than synchronising HTML and UI events, this just synchronises (JSON-serialisable) state.

Topics can be shared between connected users, and each client can subscribe to multiple topics. The library takes care of starting topic instances (GenServer processes) as needed, then shuts them down when they're no longer in use. A topic is defined with an initialisation function (which can be used to load the initial state and/or subscribe to updates from a database/etc), and can then respond to requests/notifications from clients, or arbitrary BEAM messages, to efficiently update (and synchronise) state.

The library can be used directly from Elixir, or there's a Cowboy adapter that can be used along with the JavaScript client or React hook.

I've put together a few very basic examples. Some use cases I think this works great for are, a) synchronising ephemeral state (e.g., cursor positions); b) as a layer over a database for synchronising real-time updates to persisted state. In particular, this works pretty well for event-sourcing-type scenarios - you can load events from the database, subscribe to updates, and (if needed) periodically take snapshots of the state.

Please let me know what you think.

https://github.com/joefreeman/topical