startBackgroundRefresh method

Future<void> startBackgroundRefresh()

Start background token refresh. Call this after successful authentication. The timer will automatically refresh tokens before they expire. Only refreshes when the app is in the foreground.

Implementation

Future<void> startBackgroundRefresh() async {
  // Subscribe to foreground/background events
  _fgbgSubscription?.cancel();
  _fgbgSubscription = FGBGEvents.instance.stream.listen((event) async {
    _isInForeground = event == FGBGType.foreground;

    if (_isInForeground) {
      // App came to foreground - check if we need to refresh
      final jwt = await getStoredJWT();
      if (jwt != null) {
        if (willExpireSoon(jwt, refreshBuffer)) {
          // Token expired or expiring soon while in background, refresh now
          await _performRefresh();
        } else {
          // Reschedule the background refresh
          _scheduleBackgroundRefresh(jwt);
        }
      }
    } else {
      // App went to background - cancel the timer
      _backgroundRefreshTimer?.cancel();
      _backgroundRefreshTimer = null;
    }
  });

  final jwt = await getStoredJWT();
  if (jwt != null) {
    _scheduleBackgroundRefresh(jwt);
  }
}