handleAboutToLogOut method
Public handler for pre-logout cleanup.
Can be passed to AuthService constructor for race-free initialization. See plan.auth-race.md for usage patterns.
This performs backend token unregistration (unless DeviceService handles it) and is called BEFORE Firebase signOut while still authenticated.
Implementation
Future<void> handleAboutToLogOut() async {
logd('NotificationService: handleAboutToLogOut called');
// When DeviceService is registered and connected, it handles backend cleanup
// by deleting the device doc via its own onAboutToLogOut callback.
// NotificationService should not trigger a token persistence write that
// would race with deletion.
//
// DATA MODEL ASSUMPTION: The FCM token is stored inside the device document,
// not in a separate collection. Therefore, when DeviceService deletes the
// device document on logout, the FCM token is automatically cleaned up.
// If this data model changes (e.g., tokens stored separately), this logic
// must be revisited to ensure NotificationService performs its own cleanup.
if (GetIt.I.isRegistered<DeviceServiceInt>()) {
final deviceService = GetIt.I.get<DeviceServiceInt>();
if (deviceService.isConnectedToAuth) {
logd('NotificationService: handleAboutToLogOut - DeviceService is connected, '
'skipping token persistence (device doc will be deleted by DeviceService)');
return;
}
}
// Fallback for apps without DeviceService integration or when DeviceService
// is not connected - perform backend token unregistration via the custom callback
logd('NotificationService: handleAboutToLogOut - Performing backend token unregistration');
if (_onTokenChanged != null && _cachedFcmToken != null) {
try {
await _onTokenChanged!(null, _cachedFcmToken);
logd('NotificationService: Successfully unregistered FCM token on backend before logout');
} catch (e) {
logw('NotificationService: Failed to unregister FCM token on backend: $e');
// Continue with logout even if backend call fails
}
}
}