getPermissionStream method

  1. @override
Stream<DeviceLocationPermission> getPermissionStream({
  1. Duration pollingInterval = const Duration(seconds: 1),
})
override

Implementation

@override
Stream<DeviceLocationPermission> getPermissionStream({
  Duration pollingInterval = const Duration(seconds: 1),
}) {
  final controller = StreamController<DeviceLocationPermission>.broadcast();
  StreamSubscription<web.Event>? changeSub;
  Timer? timer;

  Future<void> emitCurrent() async {
    if (controller.isClosed) return;
    try {
      final permission = await checkPermission();
      if (!controller.isClosed) controller.add(permission);
    } on Exception catch (e) {
      if (!controller.isClosed) controller.addError(e);
    }
  }

  controller.onListen = () {
    emitCurrent();
    try {
      web.window.navigator.permissions
          .query(_PermissionDescriptor(name: 'geolocation'))
          .toDart
          .then((status) {
            if (controller.isClosed) return;
            void listener(web.Event event) => emitCurrent();
            status.addEventListener('change', listener.toJS);
            changeSub = _EventStreamSubscription(
              () => status.removeEventListener('change', listener.toJS),
            );
          });
    } catch (_) {
      // Permissions API not supported; polling covers it.
    }
    timer = Timer.periodic(pollingInterval, (_) => emitCurrent());
  };

  controller.onCancel = () async {
    await changeSub?.cancel();
    timer?.cancel();
  };

  return controller.stream;
}