Sharing Supabase Subscriptions Across Ligtas Map Views

Dalrymple Ramos
Ligtas Dagupan product preview
table of contents

Ligtas Dagupan has several views of the same incident and relief data. Opening two consumers should not accidentally create two independent subscriptions to the same table.

My map-data refactor separates cached records from realtime channel ownership. The Ligtas Dagupan case study covers the broader coordination prototype.

Let the query cache own the records#

The map hook uses shared query keys for incidents, offers, and offices. Incident and offer queries have a thirty-second stale window and disable refetching on window focus.

Realtime events invalidate the relevant query key. They do not patch a second, independently maintained array inside the channel callback. Refetching through the same query function keeps the event path and the initial load path aligned.

Count consumers of each channel#

A module-level map stores a table channel and its reference count. Acquiring an existing subscription increments that count. Releasing a consumer decrements it; the last release removes the Supabase channel and its registry entry.

Consider a map and a second incident consumer. The first mount acquires the channel at count one. The second raises it to two. Closing either leaves the other subscribed; closing both removes the channel. A cleanup that removed the channel on every unmount would disconnect the remaining view.

The same pattern needs balanced acquisition and cleanup. A leaked reference would keep a channel alive, while duplicate cleanup could remove it too early. Component lifecycle behavior is therefore part of the review.

Keep different refresh policies explicit#

Offices use a different policy: they refetch when the map mounts rather than receiving the same realtime subscription treatment. Shared data does not require every table to have identical update behavior.

This implementation makes subscription ownership easier to reason about. It does not establish a measured reduction in network traffic or a guarantee of emergency-data freshness. Those outcomes need runtime observation, including reconnect behavior and delayed updates.