build method

  1. @override
NextAuthState<T> build()

Initialize a Notifier.

It is safe to use Ref.watch or Ref.listen inside this method.

If a dependency of this Notifier (when using Ref.watch) changes, then build will be re-executed. On the other hand, the Notifier will not be recreated. Its instance will be preserved between executions of build.

If this method throws, reading this provider will rethrow the error.

Implementation

@override
NextAuthState<T> build() {
  // directly read client from provider (synchronous)
  final client = ref.watch(_nextAuthClientProvider) as NextAuthClient<T>?;
  if (client == null) {
    return NextAuthState<T>(status: SessionStatus.initial);
  }

  // if client changed, cleanup old subscriptions
  if (_client != client) {
    _dispose();
    _client = client;
  }

  _storedRefetchInterval = ref.watch(_refetchIntervalProvider);
  _storedRefetchOnWindowFocus = ref.watch(_refetchOnWindowFocusProvider);
  ref.listen(authEventStreamProvider, (prev, next) {
    next.whenData((event) {
      if (event == null) return;
      if (event is SessionChangedEvent) {
        _handleSessionChanged(event.session as T?);
      } else if (event is StatusChangedEvent) {
        _handleStatusChanged(event.status);
      }
    });
  });

  if (!_isObserverAdded) {
    WidgetsBinding.instance.addObserver(this);
    _isObserverAdded = true;
  }

  ref.onDispose(() {
    _dispose();
  });

  if (_storedRefetchInterval != null && _storedRefetchInterval! > 0) {
    _startRefetchTimer(_storedRefetchInterval!);
  }

  // return the latest state from client
  return NextAuthState<T>(session: client.session, status: client.status);
}