Aguxez

Aguxez

Displaying data from database in real time in Phoenix

I have a question about broadcasting data from Postgres. I understand the way that you could do this if you’re building for example a chat application using Javascript, etc, etc… but what I had in mind is some kind of counter that is updated when someone interacts with a specific bot, for example, from top of my mind, there’s a big number (Just 1 number) in the web page and someone sends a message to the bot saying that he wants to add 10 to that number then the number updates in real time when the transaction to the database is done, my question is. How can I update this from channels or something else? Do I still need the JavaScript to interact with he DOM in real time? Perhaps use something like RethinkDB? I’m pretty lost with the implementation in this one.

Marked As Solved

Qqwy

Qqwy

TypeCheck Core Team

I now am at a computer, so it is easier to mock out a code example.

This is what I have done lately for a proof-of-concept ‘online game’, where game state is regularly updated, and then pushed towards all connected players. It does not depend on a database, since updating the data usually does not depend on the database (unless another application connects directly with the database, in which case Boltun might be what you want).

In the module that maintains the player state, I run the following function when this is updated:

  defp broadcast_update(state) do
    Phoenix.PubSub.broadcast(OnlineGame.PubSub, "player_state_update:#{state.user_id}", {:player_state_update, state})
  end

(Note that OnlineGame.PubSub is the name configured for Phoenix Pubsub, see your Phoenix config file, it will by default be MyAppName.PubSub.)

This will send an update to any other process that would like to listen to the player_state_update:2 topic.
To subscribe a Phoenix Channel to this, which forwards the information over a Phoenix Channel to a user’s Browser, I have the following

code in the channel:

defmodule OnlineGame.Web.GameChannel do
  use Phoenix.Channel

  def join("player_state_update", _params, socket) do
    user_id = get_user_id_in_some_way()
    Phoenix.PubSub.subscribe(OnlineGame.PubSub, "player_state_update:#{user_id}")
    # Some other stuff not relevant for this example, and finally:
    {:ok, socket}
  end

  def handle_info({:player_state_update, player_state}, socket) do
    push socket, "player_state_update", player_state
    {:noreply, socket}
  end
end

So you just override the handle_info from another GenServer. Note that, since the process just receives the message without being given information about what topic it was the message arrived on, it makes sense to send a tuple like this.
The implementation of handle_info here just forwards the information to the socket.

The cool thing about this approach, is that my Game context does not need to know that I use Phoenix. (But just that I use Phoenix.PubSub). I could register to this update in any other location of the application.

Also Liked

yurko

yurko

If I understand correctly then you can use a GenServer with an optional PubSub abstraction to achieve that and use database for persistence without building the whole thing around the database.

Say you have a GenServer that loads its initial state (number) from the database and has a function that updates (or adds to) this number, this function can be used anywhere in the application.

To be able to notify other processes about changes, this GenServer can store a list of pids and send messages to them or use one of existing abstractions, registry would do good.

Web layer: the webpage should have a channel connected and subscribed to changes (in join function), it will then receive updates and can act accordingly (e.g. push changed number to the client where the DOM can be updated).

Finally the database: depending on the number of updates you could subscribe to the same GenServer and update the table on each change or (if that happens a lot) add another lightweight GenServer, it can fetch the state from the publisher onece every minute or every X seconds and update the database.

Qqwy

Qqwy

TypeCheck Core Team

Good news! The hard work to send updates to other places in your application is already done for you by Phoenix.PubSub. There is no need to re-build it yourself (storing a list of pids, handle pids disappearing and reappearing, etc).

Depending on the scope of your application, you might either allow the location that performs the update send a broadcast to the registered Phoennix channels directly, or add a layer of indirection by manually subscribing your channels to a manually made PubSub location, in which case the broadcasting location does not need to know anything about the existence of a web layer (and you might be able to reuse it later for other types of data pushing).

brightball

brightball

You can also use Boltun to take advantage of Postgres LISTEN/NOTIFY if you do want to build it around the DB.

Last Post!

Qqwy

Qqwy

TypeCheck Core Team

Ah yes, in my code the player_state happens to be a Struct, which happens to be a map.
Nicer would be to transform it in a special representation to ensure only publicly available data will be shown, of course.

Glad to have helped :smiley: .

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement