Phoenix.PubSub

Serves as a Notification and PubSub layer for broad use-cases. Used internally by Channels for pubsub broadcast.

PubSub Adapter Contract

PubSub adapters need to only implement start_link/2 and respond to a few process-based messages to integrate with Phoenix.

PubSub functions send the following messages:

Additionally, adapters must implement start_link/2 with the following format:

def start_link(pubsub_server_name_to_locally_register, options)

Offloading work to clients via MFA response

The Phoenix.PubSub API allows any of its functions to handle a response from the adapter matching {:perform, {m, f, a}}. The PubSub client will recursively invoke all MFA responses until a result is returned. This is useful for offloading work to clients without blocking in your PubSub adapter. See Phoenix.PubSub.PG2 for an example usage.

Example

iex> PubSub.subscribe MyApp.PubSub, self, "user:123"
:ok
iex> Process.info(self)[:messages]
[]
iex> PubSub.broadcast MyApp.PubSub, "user:123", {:user_update, %{id: 123, name: "Shane"}}
:ok
iex> Process.info(self)[:messages]
{:user_update, %{id: 123, name: "Shane"}}
Source

Summary

broadcast!(server, topic, message)

Broadcasts message on given topic raises Phoenix.PubSub.BroadcastError if broadcast fails

broadcast(server, topic, message)

Broadcasts message on given topic

broadcast_from!(server, from_pid, topic, message)

Broadcasts message to all but sender on given topic raises Phoenix.PubSub.BroadcastError if broadcast fails

broadcast_from(server, from_pid, topic, message)

Broadcasts message to all but sender on given topic

subscribe(server, pid, topic, opts \\ [])

Subscribes the pid to the PubSub adapter’s topic

unsubscribe(server, pid, topic)

Unsubscribes the pid from the PubSub adapter’s topic

Functions

broadcast(server, topic, message)

Broadcasts message on given topic

Source
broadcast!(server, topic, message)

Broadcasts message on given topic raises Phoenix.PubSub.BroadcastError if broadcast fails

Source
broadcast_from(server, from_pid, topic, message)

Broadcasts message to all but sender on given topic

Source
broadcast_from!(server, from_pid, topic, message)

Broadcasts message to all but sender on given topic raises Phoenix.PubSub.BroadcastError if broadcast fails

Source
subscribe(server, pid, topic, opts \\ [])

Subscribes the pid to the PubSub adapter’s topic

  • server - The Pid registered name of the server
  • pid - The subscriber pid to receive pubsub messages
  • topic - The topic to subscribe to, ie: "users:123"
  • opts - The optional list of options. Supported options

    only include `:link` to link the subscriber to
         the pubsub adapter
Source
unsubscribe(server, pid, topic)

Unsubscribes the pid from the PubSub adapter’s topic

Source