Real-time Subscriptions
Relevant source files
The following files were used as context for generating this wiki page:The ElmecV2 application leverages Supabase Realtime to deliver live updates and create a dynamic, interactive user experience, primarily within the Chat module. This system enables features such as instant messaging, message status updates, and presence tracking for typing indicators, providing a user experience similar to modern messaging apps like WhatsApp. The core implementation is centralized within the ChatContext, which manages subscriptions and state updates.
The real-time functionality is a key technical feature of the application, ensuring that data is synchronized across clients with low latency.
Sources: README.md, VALIDACION-COMPLETA.md, REPORTE_CHAT_MODULE.md
Architecture Overview
The real-time architecture is client-driven, with the React Native application establishing WebSocket connections to Supabase channels. The ChatContext acts as the central manager for all real-time subscriptions. It is responsible for creating, managing, and cleaning up channels for chat rooms and user presence.
This diagram illustrates the high-level data flow for real-time events.
Sources: REPORTE_CHAT_MODULE.md, FIXES-APLICADOS.md
Subscription Types
The system utilizes three main types of real-time subscriptions, all managed within ChatContext.tsx.
1. Message Subscriptions
These subscriptions listen for database changes on the messages table. This allows the application to receive new messages and updates to existing ones (e.g., edits, soft deletes) instantly.
- Event
INSERT: Triggered when a new message is added to a chat room. The app receives the new message payload, updates the local state, and can trigger a notification. - Event
UPDATE: Triggered when a message is edited or soft-deleted. The app updates the specific message in its local state.
Sources: REPORTE_CHAT_MODULE.md, FIXES-APLICADOS.md:41-63
New Message Flow
The following sequence diagram shows how a new message is sent and received in real-time by another user.
Sources: REPORTE_CHAT_MODULE.md
Implementation Snippet
The subscription is configured to listen for INSERT and UPDATE events on the messages table, filtered by chat_room_id.
// Source: REPORTE_CHAT_MODULE.md (citing contexts/ChatContext.tsx:191-284)
const channel = supabase
.channel(`chat_room_${roomId}`)
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'messages',
filter: `chat_room_id=eq.${roomId}`
}, async payload => {
// Actualiza messages state
// Envía notificación
})
.on('postgres_changes', {
event: 'UPDATE',
schema: 'public',
table: 'messages'
}, payload => {
// Actualiza mensaje editado
})
.subscribe();
Sources: REPORTE_CHAT_MODULE.md
2. Chat Room Subscriptions
To notify users when they are added to a new chat room, a separate subscription listens for INSERT events on the chat_rooms table. This ensures the user's list of conversations is always up-to-date.
// Source: REPORTE_CHAT_MODULE.md (citing contexts/ChatContext.tsx:286-353)
const chatRoomsChannel = supabase
.channel('chat_rooms_changes')
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'chat_rooms'
}, async payload => {
// Agrega nueva sala
// Notifica usuario
})
.subscribe();
Sources: REPORTE_CHAT_MODULE.md
3. Presence Tracking (Typing Indicators)
The application uses Supabase's Presence feature to track user activity within a chat room, such as typing. This is not based on database changes but on explicit tracking events sent by the client.
- The
channel.track()method is called to send the user's status (e.g.,typing: true). - Other clients in the same channel receive this event and can update their UI to show a "typing..." indicator.
Sources: REPORTE_CHAT_MODULE.md, scripts/test-chat-module.js:688-735
Typing Indicator Flow
This diagram shows how the typing indicator status is shared between users.
Sources: REPORTE_CHAT_MODULE.md
Implementation Snippet
The sendTypingIndicator function uses channel.track() to broadcast the user's typing status.
// Source: REPORTE_CHAT_MODULE.md (citing contexts/ChatContext.tsx:534-552)
const sendTypingIndicator = (roomId, isTyping) => {
channel.track({
user_id: user.id,
user_name: `${user.nombre} ${user.apellido_paterno}`,
typing: true,
timestamp: Date.now()
});
};
Sources: REPORTE_CHAT_MODULE.md
Testing Real-time Functionality
The real-time features are validated through a dedicated test script, scripts/test-chat-module.js. This script simulates client behavior to ensure subscriptions and presence work as expected.
| Test Area | Description | Status |
|---|---|---|
| Message Subscription | Subscribes to a channel, inserts a new message into the database, and waits to receive the corresponding postgres_changes event. It uses a 10-second timeout to detect failures. | ✅ Implemented |
| Presence Tracking | Creates a channel with presence enabled, uses channel.track() to broadcast a user's status, and listens for join and sync events to confirm the presence state is updated. | ✅ Implemented |
Sources: scripts/test-chat-module.js:621-735
A Realtime TIMED_OUT error was noted during testing, but this was attributed to the Node.js test environment not maintaining a persistent WebSocket connection, rather than an issue with the application's implementation.
Sources: REPORTE_CHAT_MODULE.md
Conclusion
The real-time subscription system is a cornerstone of the ElmecV2 application's chat functionality. It is robustly implemented using Supabase's Realtime and Presence features, with a clear separation of concerns within the ChatContext. The architecture supports instant delivery of new messages, message updates, and user presence indicators, providing a modern and responsive user experience. The implementation has been verified as correct, with automated tests in place to validate core real-time operations.
Sources: REPORTE_CHAT_MODULE.md, VALIDACION-COMPLETA.md, FIXES-APLICADOS.md