Files
lab-app/lib/core/services/realtime_service.dart
2026-06-20 18:24:40 +03:00

50 lines
1.1 KiB
Dart

import 'package:pocketbase/pocketbase.dart';
import '../api/pocketbase_client.dart';
typedef UnsubFn = Future<void> Function();
class RealtimeService {
RealtimeService._();
static final instance = RealtimeService._();
final _pb = PocketBaseClient.instance.pb;
UnsubFn watch(
String collection, {
String topic = '*',
String filter = '',
required void Function(RecordSubscriptionEvent) onEvent,
}) {
UnsubFn? cancel;
bool disposeRequested = false;
bool disposed = false;
_pb
.collection(collection)
.subscribe(topic, onEvent, filter: filter)
.then((fn) async {
if (disposeRequested) {
disposed = true;
await fn();
return;
}
cancel = fn;
}).catchError((_) {});
return () async {
if (disposed) return;
disposeRequested = true;
try {
final fn = cancel;
if (fn != null) {
disposed = true;
await fn();
}
} catch (_) {
// swallow — never globally unsubscribe the topic here, because
// other screens may still be subscribed to the same collection/topic.
}
};
}
}