Skip to content

Commit bd7fb4c

Browse files
committed
refactor(push-notification): improve device token map population and deletion process
- Use `putIfAbsent` for concise and efficient population of userDeviceTokensMap - Replace sequential device deletion with parallel deletion using `Future.wait` for improved performance
1 parent 2582349 commit bd7fb4c

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

lib/src/services/push_notification_service.dart

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -193,12 +193,9 @@ class DefaultPushNotificationService implements IPushNotificationService {
193193
for (final device in targetedDevices) {
194194
final token = device.providerTokens[primaryProvider];
195195
if (token != null) {
196-
// If the user's list doesn't exist, create it.
197-
if (!userDeviceTokensMap.containsKey(device.userId)) {
198-
userDeviceTokensMap[device.userId] = [];
199-
}
200-
// Add the token to the user's list.
201-
userDeviceTokensMap[device.userId]!.add(token);
196+
// The `putIfAbsent` method provides a concise way to ensure the list
197+
// exists before adding the token to it.
198+
userDeviceTokensMap.putIfAbsent(device.userId, () => []).add(token);
202199
}
203200
}
204201

@@ -310,14 +307,11 @@ class DefaultPushNotificationService implements IPushNotificationService {
310307
);
311308

312309
try {
313-
// Delete the devices one by one.
314-
// While this is less efficient than a bulk delete, it is necessary
315-
// as `DataRepository` does not have a `deleteAll` method.
316-
await Future.forEach<PushNotificationDevice>(devicesToDelete.items, (
317-
device,
318-
) async {
319-
await _pushNotificationDeviceRepository.delete(id: device.id);
320-
});
310+
// Delete the devices in parallel for better performance.
311+
final deleteFutures = devicesToDelete.items.map(
312+
(device) => _pushNotificationDeviceRepository.delete(id: device.id),
313+
);
314+
await Future.wait(deleteFutures);
321315

322316
_log.info('Successfully cleaned up invalid device tokens.');
323317
} catch (e, s) {

0 commit comments

Comments
 (0)