프레즌스와 실시간 데이터 업데이트
애플리케이션에 프레즌스 추적을 추가하고 동적 사용자 인터페이스의 실시간 데이터 업데이트를 관리합니다.
프레즌스와 실시간 데이터 업데이트은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is User Presence?
In real-time applications, presence refers to tracking who is currently online, active, or viewing a specific resource.
- Think of a chat application showing 'online' status.
- Or a collaborative document editor indicating who else is viewing or editing.
- It's crucial for dynamic, interactive user interfaces.
Phoenix.Presence Explained
Phoenix Framework provides a powerful, built-in module called Phoenix.Presence to manage presence information.
- It leverages Elixir's concurrency and distribution features.
- It automatically handles users joining, leaving, and even network disconnections.
- This makes building robust presence features much simpler.
Integrating Presence in Channels
To use Phoenix.Presence, you typically integrate it into your Phoenix Channel modules.
First, ensure your UserSocket defines a pubsub_server (e.g., MyApp.PubSub). Then, within your channel module, you add use Phoenix.Presence.
This mixin provides helpers for tracking and retrieving presence data.
Tracking Users with `track/3`
The core function for adding a user to presence is Phoenix.Presence.track/3.
- It takes the socket, a unique key (e.g., user ID), and metadata (e.g., username, status).
- You usually call this in your channel's
join/3callback. - When a user joins a channel, they are tracked; when they leave, their presence is automatically removed.
Example: Basic Presence Track
Let's see how track/3 is called when a user joins a channel. We'll simulate a socket for this example.
defmodule MyRoomChannel do
use Phoenix.Channel
use Phoenix.Presence
@impl true
def join("room:lobby", _payload, socket) do
# In a real app, user_id would come from auth
user_id = "user_#{System.unique_integer([:positive])}"
metadata = %{username: "Guest_#{user_id}", status: "online"}
# Track the user's presence for this topic
Phoenix.Presence.track(socket, user_id, metadata)
IO.puts "User #{user_id} joined and tracked in room:lobby"
{:ok, socket}
end
# Minimal run_example to simulate join
def run_example do
mock_socket = %{topic: "room:lobby", assigns: %{}}
join("room:lobby", %{}, mock_socket)
end
end
MyRoomChannel.run_example()Accessing Presence Information
Once users are tracked, you can retrieve their presence information:
Phoenix.Presence.list(socket): Returns a map of all presences for the channel's topic.Phoenix.Presence.get_by_key(socket, user_key): Retrieves presence data for a specific user key.
These functions allow you to build dynamic UI elements based on who is online.
Live Data Updates Concept
Beyond just knowing who is online, real-time apps often need to push live data updates to clients.
- This could be a new chat message, a score update in a game, or a change in a shared item's status.
- The key is to send structured data to all connected clients on a specific channel topic.
- Clients then receive this data and update their UI accordingly.
Broadcasting Data with `broadcast!`
You can send live data updates using the broadcast!/3 function (or push/3 for direct messages) from your channel or another process.
broadcast!(socket, "event_name", %{data: "payload"}): Sends an event and payload to all clients subscribed to thesocket's topic.- The
"event_name"helps clients differentiate between types of updates.
This is how you keep all connected clients in sync with server-side changes.
Example: Broadcasting Live Data
Here's how you might broadcast a new message to all clients in a room. We simulate the broadcast call.
defmodule MyDataUpdater do
# We use Phoenix.Channel for its broadcast! helper
use Phoenix.Channel
# Function to simulate sending an update
def send_new_message(topic, sender, text) do
event = "new_message"
payload = %{sender: sender, text: text, timestamp: System.system_time(:second)}
# In a real app, you'd call broadcast! from a channel context
# or use Phoenix.PubSub.broadcast from a GenServer.
# For this runnable example, we'll just demonstrate the payload.
IO.puts "Simulating broadcast to '#{topic}' with event '#{event}' and payload:"
IO.inspect payload
:ok
end
# To run this example
def run_example do
send_new_message("room:lobby", "Alice", "Hello everyone!")
end
end
MyDataUpdater.run_example()Presence & Updates Check
Which of the following statements about Phoenix.Presence and live data updates are TRUE?
Summary: Presence & Live Data
Great job! You've learned how Phoenix.Presence simplifies tracking user activity in real-time applications.
- We covered using
Phoenix.Presence.track/3to mark users as present. - You also saw how to retrieve presence information with
list/1andget_by_key/2. - Finally, we explored sending dynamic live data updates to clients using
broadcast!/3for interactive UIs.
These tools are fundamental for building engaging real-time features!
자주 묻는 질문
“프레즌스와 실시간 데이터 업데이트” 강의는 무료인가요?
네 — “프레즌스와 실시간 데이터 업데이트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“프레즌스와 실시간 데이터 업데이트”에서 뭘 배우나요?
애플리케이션에 프레즌스 추적을 추가하고 동적 사용자 인터페이스의 실시간 데이터 업데이트를 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“프레즌스와 실시간 데이터 업데이트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Phoenix Channels 입문
- 브로드캐스팅과 Pub/Sub 메시징
- 프레즌스와 실시간 데이터 업데이트
- 채널 인증 및 권한 부여