Skip to content

Commit e4871b7

Browse files
committed
refactor(offline_playlist_service): implement cancellation of active downloads before deletion
1 parent 36a5591 commit e4871b7

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

lib/services/playlist_download_service.dart

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -407,10 +407,32 @@ class OfflinePlaylistService {
407407
}
408408

409409
Future<void> deleteAllDownloads() async {
410+
// Cancel all active downloads first and wait for them to stop
411+
final activeIds = List<String>.from(activeDownloads);
412+
for (final id in activeIds) {
413+
final notifier = downloadProgressNotifiers[id];
414+
if (notifier != null) {
415+
notifier.value.isCancelled = true;
416+
notifier.notifyListeners();
417+
}
418+
}
419+
420+
const maxWaitTime = Duration(seconds: 30);
421+
final startTime = DateTime.now();
422+
while (activeDownloads.isNotEmpty) {
423+
if (DateTime.now().difference(startTime) > maxWaitTime) {
424+
logger.log('Timeout waiting for downloads to cancel before delete');
425+
activeDownloads.clear();
426+
break;
427+
}
428+
await Future.delayed(const Duration(milliseconds: 100));
429+
}
430+
410431
try {
411432
final tracksDir = Directory('$applicationDirPath/${FilePaths.tracksDir}');
412-
final artworksDir =
413-
Directory('$applicationDirPath/${FilePaths.artworksDir}');
433+
final artworksDir = Directory(
434+
'$applicationDirPath/${FilePaths.artworksDir}',
435+
);
414436

415437
if (await tracksDir.exists()) {
416438
await tracksDir.delete(recursive: true);
@@ -426,6 +448,12 @@ class OfflinePlaylistService {
426448

427449
offlinePlaylists.value = [];
428450

451+
for (final notifier in downloadProgressNotifiers.values) {
452+
notifier.dispose();
453+
}
454+
downloadProgressNotifiers.clear();
455+
activeDownloads.clear();
456+
429457
unawaited(addOrUpdateData('userNoBackup', 'offlineSongs', []));
430458
unawaited(addOrUpdateData('userNoBackup', 'offlinePlaylists', []));
431459

0 commit comments

Comments
 (0)