observe method
- String key,
- void listener(
- String? value,
- Participant? updatedBy
The observe() method subscribes listener to real-time updates for a given key. When the key’s value changes, listener runs for every participant observing it.
Key Notes:
- The listener itself identifies the observation: pass the same one to stopObserving.
- The listener receives the new value and who updated it.
- Ideal for syncing live data like timers, shared notes, or agendas.
- Throws if the room has not been joined yet or the request fails.
- An empty
keyobserves nothing.
Parameters
key- The key to observe.listener- Function triggered on each update. Receives:value(String?) → Updated value ornullif deletedupdatedBy(Participant?) → Object of participant who made the update
Example
void onBlockChat(String? value, Participant? updatedBy) {
print("Updated by: ${updatedBy?.id}");
}
await room.realtimeStore.observe("BLOCK_CHAT", onBlockChat);
Implementation
Future<void> observe(
String key,
void Function(String? value, Participant? updatedBy) listener,
) async {
if (key.trim().isEmpty) return;
if (_realtimeStoreEventEmitter == null) {
throw Exception("EventEmitter is not initialized");
}
if (!_ensureJoined("realtimeStore.observe")) return;
final listeners = _observers.putIfAbsent(key, () => {});
if (listeners.containsKey(listener)) return;
void onEvent(event) {
if (event != null) {
listener(event['value'] as String?, event['updatedBy'] as Participant?);
}
}
//Registered before the request goes out, then unwound if it fails: the
//server can push the current value as soon as it acks the observe.
listeners[listener] = onEvent;
_realtimeStoreEventEmitter!.on(key, onEvent);
try {
await _observeInternal(key);
} catch (_) {
_realtimeStoreEventEmitter!.remove(key, onEvent);
listeners.remove(listener);
rethrow;
}
}