Best way to publish model (context) changes to a channel in phoenix 1.3?

I want to publish create/update/delete events to a channel.

Is it ok to put AppNameWeb.Endpoint.broadcast() calls in context file?

For example:

defmodule PhoenixLibrary.Books do
  ...
  def delete_book(%Book{} = book) do
    PhoenixLibraryWeb.Endpoint.broadcast("books:updates", "delete", %{id: book.id})
    ...
  end
  ...
end

I read somewhere that “phoenix way” is to store such code in controller. But I would like to publish those changes even if user changed record from console or admin panel (like ex_admin).

It is possible to use Phoenix.PubSub directly, which separates the ‘web’ concern with the ‘publish/subscribe’ functionality. Using the second from within any of your contexts is not a problem at all: In fact, it allows any of the other contexts to listen for changes in your data, regardless of if that is sent to the browser, or logged somewhere, etc.

You can then in your Phoenix Channel file state that the channel should also listen to the mentioned broadcast event, and then you can proceed in the channel as normal.

2 Likes