initialize method

  1. @override
Future<void> initialize({
  1. required AuthServiceInt authService,
})
override

Initializes DeviceService with auth reference for race-free setup.

Call this AFTER creating AuthService with callbacks pre-registered. This sets up the auth reference and lifecycle service connection without registering callbacks (since they were passed to AuthService).

Critical Constraint

The implementation MUST set _authService synchronously at the start, before any await statements. This ensures the auth reference is available when callbacks fire (which may happen via microtask immediately after AuthService construction).

Usage

// Race-free initialization pattern:
final deviceService = DeviceServiceImpl();
final auth = AuthServiceImpl(
  firebaseApp: app,
  onAuthenticatedCallbacks: [deviceService.handleAuthenticated],
  onAboutToLogOutCallbacks: [deviceService.handleAboutToLogOut],
);

// CRITICAL: Use Future.wait for parallel initialization
await Future.wait([
  deviceService.initialize(authService: auth),
  notificationService.initialize(authService: auth),
]);

Parameters

  • authService: The AuthService instance to connect to.

Implementation

@override
Future<void> initialize({required AuthServiceInt authService}) async {
  // CRITICAL: Set _authService FIRST, before any await statements.
  //
  // The auth callback (handleAuthenticated) may fire immediately after
  // AuthService construction via a microtask. If we await anything before
  // setting _authService, the callback could execute while _authService
  // is still null, breaking dependent operations.
  //
  // See: "Critical implementation constraints" section in plan.auth-race.md
  _authService = authService;
  _isConnectedToAuthService = true;

  // Connect to lifecycle service for automatic resume updates.
  // This is synchronous and does not await.
  _connectToLifecycleService();

  logd('DeviceService: Initialized with auth service');
}