addOnAuthenticatedCallback method

  1. @override
void addOnAuthenticatedCallback(
  1. Future<void> callback(
    1. String? uid
    ), {
  2. int priority = 0,
})
override

Add a callback to be invoked when user authenticates.

The callback receives the user's UID (or null if unavailable).

priority determines execution order:

  • Higher values execute first (priority 100 runs before priority 0)
  • Same priority callbacks execute in parallel
  • Default is 0

Implementation

@override
void addOnAuthenticatedCallback(
  Future<void> Function(String? uid) callback, {
  int priority = 0,
}) {
  _onAuthenticatedByPriority.putIfAbsent(priority, () => []).add(callback);

  // Replay-on-register (BehaviorSubject semantics, Issue 99).
  //
  // When the init chain moved behind the app-init gate, a callback registered
  // AFTER DreamicServices.initialize (because its target services are
  // constructed post-init — e.g. a RevenueCat / tiering / user-doc service)
  // could miss the warm-start auth event, which is delivered DURING
  // initialize's await. To keep a late onAuthenticated subscriber working, if
  // the initial auth event has already been delivered AND a user is currently
  // authenticated, replay it once for this callback.
  //
  // Gate on the STREAM-EVENT flags (_hasAuthStateChangeListenerRunAtLeastOnce
  // + _lastDeliveredAuthUid), NOT on currentFbUser — FirebaseAuth.currentUser
  // is populated synchronously from cache before the stream's first event, so
  // gating on it would replay AND then the listener event would fire again
  // (double-invoke). onAuthenticated ONLY — replaying logout (see
  // addOnLoggedOutCallback) would destructively tear down un-set-up state.
  if (_hasAuthStateChangeListenerRunAtLeastOnce &&
      _lastDeliveredAuthUid != null) {
    final uid = _lastDeliveredAuthUid;
    scheduleMicrotask(() async {
      try {
        await callback(uid);
      } catch (e, stackTrace) {
        loge(e, 'onAuthenticated replay-on-register callback failed',
            stackTrace);
      }
    });
  }
}