watch method

  1. @override
Stream<InputLanguage?> watch({
  1. required Duration pollInterval,
})
override

Streams the keyboard language, starting with the current value where the platform can determine it. pollInterval is used by platforms that have no change notification.

Implementation

@override
Stream<InputLanguage?> watch({required Duration pollInterval}) {
  late final StreamController<InputLanguage?> controller;
  Process? monitor;
  StreamSubscription<String>? lines;
  Timer? poll;
  var cancelled = false;

  Future<void> emitCurrent() async {
    final language = await getCurrent();
    if (!cancelled) controller.add(language);
  }

  controller = StreamController<InputLanguage?>(
    onListen: () async {
      await emitCurrent();
      if (cancelled) return;
      if (await _hasGnome()) {
        try {
          final process = await _start('gsettings', <String>[
            'monitor',
            _schema,
            'mru-sources',
          ]);
          if (cancelled) {
            process.kill();
            return;
          }
          monitor = process;
          lines = process.stdout
              .transform(utf8.decoder)
              .transform(const LineSplitter())
              .listen((_) => emitCurrent());
          return;
        } on ProcessException {
          // Fall through to polling.
        }
      }
      if (cancelled) return;
      poll = Timer.periodic(pollInterval, (_) => emitCurrent());
    },
    onCancel: () async {
      cancelled = true;
      poll?.cancel();
      await lines?.cancel();
      monitor?.kill();
    },
  );
  return controller.stream;
}