SZJX

SZJX

Presence not picking up user leave events?

I need to perform some actions when the user leaves a channel (in most cases where they close the tab voluntarily, but there may also be a connection loss/timeout etc.)

According to posts like Phoenix.Presence run some code when user leaves the channel and https://stackoverflow.com/questions/33934029/how-to-detect-if-a-user-left-a-phoenix-channel-due-to-a-network-disconnect, intercepting the "presence_diff" event from Presence seems to be a foolproof way to go, as it should also cover the cases where the connection terminates abnormally.

Strangely, the presence_diff event seems to only be triggered when I track the user via Presence.track (i.e. when the user joins), but not when the user leaves (e.g. when I close my browser tab under dev environment)

Meanwhile, adding a terminate(reason, socket) callback in my channel correctly catches the leave event.

I wonder what could be wrong in my configuration. Or did I not understand the use of Presence correctly?

Example code:

  def join("participant:" <> participant_id, _payload, socket) do
    if socket.assigns.participant_id == participant_id do
      send(self(), :after_participant_join)
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end
  
  def handle_info(:after_participant_join, socket) do
    experiment_id = socket.assigns.experiment_id

    Presence.track(socket, experiment_id, %{
      # keys to track
    })

    # Broadcast something
    # broadcast(socket, ...)
    
    {:noreply, socket}
  end

  intercept(["presence_diff"])

  def handle_out("presence_diff", payload, socket) do
    # Only gets triggered at Presence.track, but not when the connection is closed.
    IO.puts("presence_diff triggered, payload is #{inspect(payload)}")

    leaves = payload.leaves

    for {experiment_id, meta} <- leaves do
      IO.puts("Leave information: #{meta}")
      
      # Do stuffs
    end

    {:noreply, socket}
  end
  
  # This works, however.
  def terminate(reason, socket) do
    IO.puts("terminated. #{inspect(reason)}")

    # Do stuffs.
  end

Marked As Solved

SZJX

SZJX

OK I think I know what happened: Each "participant:" <> participant_id topic is, as its name suggests, only subscribed to by one participant. Therefore, when that participant quits, nobody is subscribed to the topic whatsoever. Apparently in this case the whole Presence also ceases to function.

This is not really what I expected, as I need to run some cleanup after a participant exits, but under this mechanism, whenever the last participant that’s out there exits, my callback wouldn’t be triggered at all. It appears that Presence is not suitable for this purpose.

Also Liked

michalmuskala

michalmuskala

The issue is that the presence leave event is triggered when the process dies. But the process itself is subscribed to this information, so you can’t really do anything in that process, because it is already dead. If there was a separate process listening for those events, it should work just fine.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement