postgleam/listener

Receive LISTEN/NOTIFY notifications as messages.

A listener owns a dedicated connection. Every notification on a channel it listens to is sent to the Subject given to start.

import gleam/erlang/process
import postgleam
import postgleam/listener

pub fn main() {
  let assert Ok(cfg) = config.from_url("postgres://app:secret@localhost/app")
  let inbox = process.new_subject()
  let assert Ok(l) = listener.start(cfg, inbox)
  let assert Ok(Nil) = listener.listen(l, "jobs")

  let assert Ok(conn) = postgleam.connect(cfg)
  let assert Ok(Nil) = postgleam.notify(conn, "jobs", "42")

  let assert Ok(notification) = process.receive(inbox, 1000)
  // notification.channel == "jobs", notification.payload == "42"
}

If the connection drops, the listener reconnects (retrying with backoff) and listens to its channels again. Notifications sent while it was disconnected are lost; PostgreSQL does not keep them.

Types

A running listener.

pub opaque type Listener

Messages the listener process handles.

pub opaque type Message

A notification: the channel, the payload, and the server process id of the session that sent it.

pub type Notification =
  connection.Notification

Values

pub fn listen(
  listener: Listener,
  channel: String,
) -> Result(Nil, error.Error)

Start listening on channel. Channel names are used as given (they are quoted, so they are case-sensitive).

pub fn start(
  config: config.Config,
  deliver_to: process.Subject(connection.Notification),
) -> Result(Listener, error.Error)

Start a listener with its own connection. Notifications go to deliver_to. The listener is linked to the calling process.

pub fn stop(listener: Listener) -> Nil

Stop the listener and close its connection.

pub fn unlisten(
  listener: Listener,
  channel: String,
) -> Result(Nil, error.Error)

Stop listening on channel.

✨ Search Document