Is it possible to share a Phoenix Pubsub with an external dependency?


I’m building a little web app in phoenix. I want the app to allow users to play a dice game together. I have written all the game logic and genserver implementation in a separate application called DiceGame. This is included as a dependency in the phoenix app. The dice game app has an external api like"

DiceGame.make_move(game_id, dice_guess)

So I have a Phoenix.Pubsub service running in the Phoenix app. When one player makes a move, how can the DiceGame make a Pubsub.broadcast using the Phoenix app’s pubsub service?

By using the PubSub.PG2 adapter you can send messages across servers using distributed Elixir. You just need to connect the nodes. You can use the PG2 adapter by providing the adapter child spec option when you are starting the PubSub. For example if you start it with your application your start method in your application.ex file will look like this:

def start(_type, _args) do
    children = [
      {Phoenix.PubSub, name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2},
    Supervisor.start_link(children, [])

Thank you for your response.

Could you please elaborate on some of the points?

What do you mean by “connect the nodes”?

Should the above code go in the phoenix app or the DiceGame app?

DiceGame Is probably a library, not an application…

If You created it with --sup, You will have a supervision tree, if not it is just a library

In case You have a supervision tree, You can add Phoenix Pubsub, start a node and connect with the main application. Because the BEAM makes it easy to cluster nodes and work in a distributed mode

If You have a library, You could inject a notify function

It’s an application, there is a supervision tree.

I made a post about how to connect two nodes with Phoenix pubsub…

I wrote about it last year, maybe it can help, Let's talk