initializeNotificationSync method

Future<void> initializeNotificationSync()

Initializes notification state sync with NotificationService.

This subscribes to the NotificationService badge count stream and syncs the initial permission status. Call this after NotificationService has been initialized.

Safe to call multiple times - subsequent calls are ignored.

Implementation

Future<void> initializeNotificationSync() async {
  // Already subscribed
  if (notificationBadgeSubscription != null) {
    logv('Notification sync already initialized, skipping');
    return;
  }

  try {
    final notificationService = NotificationService();

    // Only proceed if the service is initialized
    if (!notificationService.isInitialized) {
      logv('NotificationService not initialized, skipping notification sync');
      return;
    }

    logd('Initializing notification state sync');

    // Sync initial badge count
    final initialCount = notificationService.getBadgeCount();
    emitSafe(state.copyWith(unreadNotificationCount: initialCount));

    // Subscribe to badge count changes
    notificationBadgeSubscription = notificationService.badgeCountStream.listen(
      (count) {
        logv('Badge count stream update: $count');
        emitSafe(state.copyWith(unreadNotificationCount: count));
      },
      onError: (error) {
        loge('Error in notification badge stream: $error');
      },
    );

    // Sync initial permission status
    final permissionStatus = await notificationService.getPermissionStatus();
    emitSafe(state.copyWith(notificationPermissionStatus: permissionStatus));

    logd('Notification state sync initialized');
  } catch (e) {
    loge(e, 'Error initializing notification sync');
  }
}