Realtime

SupabaseRealtime (the bean supabaseRealtime) gives the three things Supabase Realtime sends, as streams: the changes of rows of the database (Postgres Changes), messages between clients (Broadcast) and who is online (Presence). Usually an application declares a @RealtimeChannel interface and the generator writes the bean.

Why

Realtime speaks the Phoenix Channels protocol over one WebSocket: topics to join, replies to match, a heartbeat, a rejoin after every reconnection, and the user's token to send again when it changes. On top, the configuration of a channel is taken at its join only. The starter does all of it: a channel is joined while something listens to it, and the application only sees streams and futures.

Example

@Introspected()
class Cursor {
  Cursor({required this.x, required this.y});

  final int x;
  final int y;
}

@Introspected()
class Member {
  Member({required this.name, this.typing = false});

  final String name;
  final bool typing;
}

@RealtimeChannel('room:{id}', presenceKey: '#{authentication.name}')
abstract interface class Room {
  @Broadcast('cursor')
  Stream<Cursor> cursors(String id);

  @Broadcast('cursor')
  Future<void> moveCursor(String id, Cursor cursor);

  @Presence()
  Stream<List<Member>> members(String id);

  @Presence()
  Future<void> join(String id, Member me);

  @PostgresChanges(table: 'messages', filter: 'room_id=eq.{id}')
  Stream<RealtimeRowChange> messages(String id);
}

@Service()
class Board {
  Board(this.room);              // the generated bean

  final Room room;

  void open(String id) {
    room.cursors(id).listen(drawCursor);     // listening joins room:<id>
    room.members(id).listen(showMembers);
    room.join(id, Member(name: 'Ann'));
  }
}

The declared channel

@RealtimeChannel(name, private:, self:, ack:, presenceKey:) marks the interface of the channel name (the topic realtime:<name>).

Option Meaning
private A channel whose members are authorized by the policies of row-level security on realtime.messages.
self This client receives its own broadcasts too.
ack A @Broadcast method that sends waits until the server took the message.
presenceKey The key this client is present under. #{authentication.name} makes the devices of one user one member. Without it the server makes one up per connection.
Method What it does
@Broadcast('event') Stream<T> name(...) The broadcasts of the other clients, each payload read as T with the ObjectMapper (a Map<String, Object?> as it is). A payload that cannot be read is an error event (MessageConversionException), and the stream goes on.
@Broadcast('event') Future<void> name(..., payload) Sends one. The payload is the parameter the channel's name does not use (or the one marked @RequestBody()), written as JSON; without one, {} is sent.
@Presence() Stream<List<T>> name(...) Everyone present, now and after each change; what each tracked is read as T (RealtimePresence gives the key and the reference too).
@Presence() Future<void> name(..., state) Makes this client present with the state, written as a JSON object.
@Presence() Future<void> name(...) Without a state parameter: ends this client's presence.
@PostgresChanges(table:, schema:, filter:, kind:) Stream<RealtimeRowChange> name(...) The changes of the rows of a table.

Changes of rows

realtime
    .postgresChanges(table: 'todos', filter: 'list_id=eq.7')
    .listen((change) {
      if (change.kind == RealtimeChangeKind.delete) {
        remove(change.oldRecord['id']);
      } else {
        put(change.record);
      }
    });

A RealtimeRowChange is one change, sent after it is committed:

Member Meaning
kind RealtimeChangeKind.insert, update or delete.
schema, table Where.
record The row after the change, column names to JSON values; empty for a delete.
oldRecord The row before an update or a delete: only the primary key, unless the table has replica identity full; empty for an insert.
commitTime When the change was committed, when the server said.
columns The PostgreSQL types of the columns, by name.
errors What the server could not do for this change, such as Error 413: Payload Too Large.

The rows are JSON, not entities. For entities, declare watch…By (Stream<List<T>>, the rows kept up to date) and changes…By (Stream<RowChange<T>>) methods on a repository: the REST data store reports the changes of its rows from here. A condition Realtime can filter (one condition with eq, neq, lt, lte, gt or gte) is filtered on the server, and anything else on this side:

@UseStore('supabase')
abstract interface class Todos implements ListCrudRepository<Todo, int> {
  Stream<List<Todo>> watchByListId(String listId);

  Stream<RowChange<Todo>> changesByListId(String listId);
}
// changesByListId('l1') joins with {event: *, schema: public, table: todos, filter: list_id=eq.l1}

watch…By runs its query when listened to and again after every change, and changes…By gives each insert, update and delete as a RowChange (previous only with replica identity full). See Data and Changes of rows.

Broadcast and presence in code

For a channel whose name or use is not known when the application is built, ask SupabaseRealtime:

final room = realtime.channel('room:42', presenceKey: userId);
room.broadcast('cursor').listen(moveCursor);
room.presence().listen(showMembers);
await room.track({'name': 'Ann'});
await room.send('cursor', {'x': 3, 'y': 4});

realtime.channel(name, private:, self:, ack:, presenceKey:) gives a RealtimeChannelSession. Every call with the same name gives the same channel; the options must be the same while it is used, or its use fails with a StateError.

Member What it does
broadcast(event) The payloads of the broadcasts named event, as JSON objects; one that is not an object is an error event.
events(event) The same, whatever their JSON (an object, a list, a text).
send(event, [payload]) Broadcasts, joining the channel first when needed. With ack it waits for the server and fails with a PhoenixPushException when the server refuses it.
presence() Who is present: the list now, then again after every change.
track(state), untrack() Makes this client present with a state (tracking again replaces it); ends its presence.
postgresChanges(table:, schema:, filter:, kind:) The changes of rows on this channel.
leave() Leaves the channel now: its streams are done. Using it again joins it again.

A RealtimePresence has the key the client joined with, the server's ref of this one presence, and the state it tracked. The same key may be present several times: a user on two devices.

The server takes the configuration of a channel at its join only. So when a stream of database changes is added or cancelled, or presence is first used, while the channel is joined, it is joined again: the other streams go on, but a broadcast sent in that moment is missed. Listen to what a channel needs at once, or give database changes a channel of their own; realtime.postgresChanges does.

The connection

Tokens

Not supported

The properties

Key Type Default Meaning
spring.supabase.realtime.heartbeat-interval Duration 25s How often the connection says it is alive. spring.websocket.client.config.supabase-realtime.phoenix.heartbeat-interval wins.
spring.supabase.realtime.timeout Duration 10s How long a join or a message waits for its answer. …supabase-realtime.phoenix.push-timeout wins.
spring.supabase.realtime.max-message-size DataSize 4MB The largest message read; a larger one closes the connection. …supabase-realtime.max-text-message-size wins.
spring.supabase.connect-timeout Duration 10s How long the connection may take to open. …supabase-realtime.connect-timeout (or default's) wins.

In Supabase (JavaScript)

realtime-js Here
supabase.channel(name, {config}) realtime.channel(name, …), or a @RealtimeChannel interface
channel.on('postgres_changes', {event, schema, table, filter}, fn) postgresChanges(table:, schema:, filter:, kind:), @PostgresChanges
channel.on('broadcast', {event}, fn), channel.send({type: 'broadcast', event, payload}) broadcast(event), send(event, payload), @Broadcast
channel.on('presence', {event: 'sync'}, fn), channel.track(state), channel.untrack() presence(), track(state), untrack(), @Presence
channel.subscribe() not needed
supabase.removeChannel(channel) leave()
realtime.setAuth() refreshAuth(), called by itself

See also