watchAdvertisements method

Future<void> watchAdvertisements([
  1. Duration? timeout
])

Watch for advertisements from this device. The advertisements will be received using the advertisements Stream. You can choose to only watch advertisements for a specific amount of times in that case use the timeout variable. If this is null then it will watch advertisements for as long as the device is in range. Do note that not every device will keep sending out advertisements.

Not every browser supports this API yet. Chrome for Windows, Linux, and probably also mac os have this hidden behind the chrome://flags/#enable-experimental-web-platform-features flag. If the API is not supported then this method will throw a NativeAPINotImplementedError use hasWatchAdvertisements to make sure that the browser supports the method. Even if the device technically has the method sometimes it won't fire any advertisement events even though the device may be sending them. This is the case with chrome for linux.

If the browser is already watching for advertisements and this is called again then nothing special will happen and it will request the device again to send advertisements.

Implementation

Future<void> watchAdvertisements([final Duration? timeout]) async {
  if (!_bluetoothDevice.hasWatchAdvertisements()) {
    // Throw the error
    return await _bluetoothDevice.watchAdvertisements();
  }
  _advertisementAbortController
      ?.abort(StateError("Can only watch the advertisements once"));

  _startAdvertisementStream();
  final controller = timeout != null ? null : AbortController();
  if (timeout != null) {
    _advertisementAbortController = controller;
  }
  final signal = timeout != null
      ? AbortSignal.timeout(timeout.inMilliseconds)
      : controller!.signal;
  try {
    final options = WatchAdvertisementsOptions(signal: signal);
    await _bluetoothDevice.watchAdvertisements(options);
  } catch (e) {
    if (e is Error) {
      rethrow;
    }
    final asString = e.toString();
    throw BrowserError(asString);
  }
}