LiveSync

coverbotHex.pmDocumentation

LiveSync allows automatic updating of LiveView assigns by utilizing postgres replication.

Installation

This project builds on top of PostgreSQL replication and it requires PostgreSQL 14+. You must also enable replication in your PostgreSQL instance:

ALTER SYSTEM SET wal_level='logical';
ALTER SYSTEM SET max_wal_senders='64';
ALTER SYSTEM SET max_replication_slots='64';

Then you must restart your database.

Add live_sync to the list of dependencies in mix.exs:

  def deps do
    [
      {:live_sync, "~> 0.1.0"}
    ]
  end

Add a migration to setup replication (requires superuser permissions to subscribe to all tables):

  defmodule MyApp.Repo.Migrations.SetupLiveSync do
    use Ecto.Migration

    def up do
      LiveSync.Migration.up()
      # If you don't have superuser you can pass specific tables
      # LiveSync.Migration.up(["table1", "table2"])
    end

    def down do
      LiveSync.Migration.down()
    end
  end

Add LiveSync to your supervision tree:

Usage

For any Ecto schemas you want to watch, add the LiveSync.Watch derive:

Add the LiveSync macro to any LiveView module you want to automatically sync data:

Handling Sync Events

An optional callback can also be added to the LiveView module to handle the updated data. This callback will be called for each assign key that is watched and changed. It must return the socket with updated assigns.

  def sync(:list_of_objects, updated, socket) do
    updates =
      updated
      |> Enum.filter(&is_nil(&1.executed_at))
      |> Enum.sort_by(& &1.name)
      |> Repo.preload([...])

    assign(socket, list_of_objects: updates)
  end