Phoenix.PubSub Documentation

repository·main·Indexed 20 days ago

https://github.com/phoenixframework/phoenix_pubsub

A distributed PubSub and Presence platform for the Phoenix Framework that enables real-time communication across multiple nodes. Includes guides on installation, initializing instances via supervision trees, and using subscribe/2 and broadcast/3 for topic-based messaging.

Tokens
484
Snippets
5
Records
5
Agent score
23%

What's inside Phoenix.PubSub

  1. Start a Phoenix.PubSub instance

    main

    To initialize Phoenix.PubSub, add it as a child to your application's supervision tree. You must provide a unique name for the PubSub instance.

    defmodule MyApp do
      use Application
    
      def start(_type, _args) do
        children = [
          {Phoenix.PubSub, name: MyApp.PubSub}
        ]
    
        opts = [strategy: :one_for_one, name: MyApp.Supervisor]
        Supervisor.start_link(children, opts)
      end
    end
  2. Broadcast and subscribe to topics

    main

    Once your PubSub instance is running, you can use Phoenix.PubSub.subscribe/2 to listen to a specific topic and Phoenix.PubSub.broadcast/3 to send messages to that topic.

    # Subscribe to a topic
    Phoenix.PubSub.subscribe(MyApp.PubSub, "user:123")
    
    # Broadcast a message to a topic
    Phoenix.PubSub.broadcast(MyApp.PubSub, "user:123", :hello_world)