RealtimeClient (Realtime Client v0.2.0) View Source

Client library to work with Realtime.

It's mostly a wrapper around Phoenix Client.

Getting started

First you have to create a client Socket:

options = [
  url: "ws://realtime-server:4000/socket/websocket",
]
{:ok, socket} = RealtimeClient.socket(options)

Once you have a connected socket, you can subscribe to topics:

{:ok, channel} = RealtimeClient.subscribe(socket, "realtime:*")

You can also subscribe to a specific channel (row level changes):

{:ok, channel} = RealtimeClient.subscribe(socket, "realtime:public:users:id=eq.42")

Consuming events is done with handle_info callbacks:

alias PhoenixClient.Message

# handle `INSERT` events
def handle_info(%Message{event: "INSERT", payload: %{"record" => record}} = msg, state) do
    # do something with record
    {:noreply, state}
end

# handle `DELETE` events
def handle_info(%Message{event: "DELETE", payload: %{"record" => record}} = msg, state) do
    IO.inspect(record, label: "DELETE")
    {:noreply, state}
end

# match all cases not handled above
def handle_info(%Message{} = msg, state) do
    {:noreply, state}
end

Configuration

Socket endpoint and parameters can also be configured:

config :realtime_client,
  endpoint: "ws://realtime-server:4000/socket/websocket",
  apikey: "eyJhbGciOiJIUzI1MiIsInR5cCI6IkpXVCJ9.eyJJc3N1ZXIiOiJJc3N1ZXIifQ.LNcM66Tt3ejSf0fHJ-I8yh8Hgfmvh8I_CXyBIOU8S6c"

Creating the socket can then be done with:

{:ok, socket} = RealtimeClient.socket()

Link to this section Summary

Functions

Creates a new client socket.

Subscribes to a topic through given socket. In cases where the socket is not connected (yet), the function is retried (see subscribe/4).

Link to this section Functions

Creates a new client socket.

  • opts - The optional list of options. See below.

Options

  • url - the url of the websocket to connect to
  • params - the params to send to the websocket, e.g. to pass an api key
Link to this function

subscribe(socket, topic)

View Source

Subscribes to a topic through given socket. In cases where the socket is not connected (yet), the function is retried (see subscribe/4).

  • socket - The name of pid of the client socket
  • topic - The topic to subscribe to
Link to this function

subscribe(socket, topic, retires, error \\ nil)

View Source