appCheckTokenChanges function

Stream<AppCheckToken> appCheckTokenChanges({
  1. String? app,
})

Tokens as they are issued, including the refreshes the SDK makes on its own.

One listener per app. deleteNamedApp ends a named app's stream.

Implementation

Stream<AppCheckToken> appCheckTokenChanges({String? app}) {
  _watchDeletes();
  final name = app == null || app.isEmpty ? null : app;
  RawReceivePort? receive;
  void Function()? end;
  late StreamController<AppCheckToken> controller;
  void drop() {
    receive?.close();
    receive = null;
    if (name != null && end != null) _changes[name]?.remove(end);
  }

  controller = StreamController<AppCheckToken>(
    onListen: () {
      final port = RawReceivePort();
      port.handler = (Object? message) {
        try {
          controller.add(_readToken(message! as Uint8List));
        } on Object catch (e) {
          controller.addError(e);
        }
      };
      final rc = _onApp(
        name,
        (a) => fdbAcAddListener(a, port.sendPort.nativePort),
      );
      if (rc != 0) {
        port.close();
        controller.addError(
          StateError(
            rc == -3
                ? 'a token listener is already registered${_on(name)}'
                : 'appCheckTokenChanges before initAppCheck${_on(name)} ($rc)',
          ),
        );
        return;
      }
      receive = port;
      if (name != null) {
        final ended = end = () {
          drop();
          unawaited(controller.close());
        };
        (_changes[name] ??= <void Function()>{}).add(ended);
      }
    },
    onCancel: () {
      // Null once the app was deleted: its listener went with it.
      if (receive == null) return;
      _onApp(name, fdbAcRemoveListener);
      drop();
    },
  );
  return controller.stream;
}