Skip to content

Instantly share code, notes, and snippets.

@jamescarr
Created August 16, 2024 18:46
Show Gist options
  • Save jamescarr/53f4d78f0fbef8331bebb9b984df5161 to your computer and use it in GitHub Desktop.
Save jamescarr/53f4d78f0fbef8331bebb9b984df5161 to your computer and use it in GitHub Desktop.

Handling different events with pattern matching.

  def handle_info(%{
      event: "presence_diff",
      topic: "user-activity"
    }, socket) do
    send_update(
      UserActivityLive,
      id: socket.assigns.user_activity_component_id)

    {:noreply, socket}
  end

  def handle_info(%{
      event: "presence_diff",
      topic: "survey-activity"
    }, socket) do
    send_update(
      SurveyActivityLive,
      id: socket.assigns.survey_activity_component_id)

    {:noreply, socket}
  end

  def handle_info(_event, socket) do
    {:noreply, socket}
  end

Or handling the event with a case.

def handle_info(%{event: "presence_diff", topic: topic} = event, socket) do
  case topic do
    "user-activity" ->
      send_update(
        UserActivityLive,
        id: socket.assigns.user_activity_component_id
      )

    "survey-activity" ->
      send_update(
        SurveyActivityLive,
        id: socket.assigns.survey_activity_component_id
      )

    _ ->
      # Handle any other topics or do nothing
      :noop
  end

  {:noreply, socket}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment