Skip to content

Commit b6d55f0

Browse files
committed
perf(push-notification): optimize push notification dispatch by grouping device tokens
This commit improves the performance of the push notification dispatch process by grouping device tokens by user ID before sending notifications. This change avoids iterating through all devices for each user, which reduces the time complexity from O(N^2) to O(N), significantly speeding up the dispatch process.
1 parent 792dbc8 commit b6d55f0

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

lib/src/services/push_notification_service.dart

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,21 @@ class DefaultPushNotificationService implements IPushNotificationService {
187187
'Found ${targetedDevices.length} devices to target via $primaryProvider.',
188188
);
189189

190+
// 6. Group device tokens by user ID for efficient lookup.
191+
// This avoids iterating through all devices for each user.
192+
final userDeviceTokensMap = <String, List<String>>{};
193+
for (final device in targetedDevices) {
194+
final token = device.providerTokens[primaryProvider];
195+
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);
202+
}
203+
}
204+
190205
// 7. Iterate through each subscribed user to create and send a
191206
// personalized notification.
192207
final sendFutures = <Future<void>>[];
@@ -214,11 +229,8 @@ class DefaultPushNotificationService implements IPushNotificationService {
214229
try {
215230
await _inAppNotificationRepository.create(item: notification);
216231

217-
// Find all device tokens for the current user.
218-
final userDeviceTokens = targetedDevices
219-
.where((d) => d.userId == userId)
220-
.map((d) => d.providerTokens[primaryProvider]!)
221-
.toList();
232+
// Efficiently retrieve the tokens for the current user from the map.
233+
final userDeviceTokens = userDeviceTokensMap[userId] ?? [];
222234

223235
if (userDeviceTokens.isNotEmpty) {
224236
// Add the send operation to the list of futures.

0 commit comments

Comments
 (0)