fix(downloads): flush queue persistence when app is backgrounded

Queue writes are debounced by 350 ms and the only guaranteed flush ran
in the provider's onDispose, which never fires when the OS kills the
backgrounded process - the most recent queue mutations were silently
lost, so items could vanish after the app sat minimised for a while.

Expose flushQueuePersistence() on the queue notifier and call it from
the app lifecycle observer on AppLifecycleState.paused, the last
reliable callback before a potential process kill.
This commit is contained in:
zarzet
2026-07-09 19:47:11 +07:00
parent d988b2c9d3
commit 60bf871945
2 changed files with 18 additions and 0 deletions
+8
View File
@@ -149,6 +149,14 @@ class _EagerInitializationState extends ConsumerState<_EagerInitialization>
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_maybeAutoScanLocalLibrary();
} else if (state == AppLifecycleState.paused) {
// Last reliable moment before the OS may kill the process: make sure
// any debounced download-queue persistence reaches disk.
if (ref.exists(downloadQueueProvider)) {
unawaited(
ref.read(downloadQueueProvider.notifier).flushQueuePersistence(),
);
}
}
}
@@ -2039,6 +2039,16 @@ class DownloadQueueNotifier extends Notifier<DownloadQueueState> {
return const DownloadQueueState();
}
/// Flush any debounced queue persistence to disk immediately. Called when
/// the app is backgrounded: the OS may kill the process without a graceful
/// teardown, and a pending debounce timer would silently drop the most
/// recent queue mutations.
Future<void> flushQueuePersistence() async {
if (_queuePersistDebounce?.isActive != true) return;
_queuePersistDebounce?.cancel();
await _flushQueueToStorage();
}
Future<void> _loadQueueFromStorage() async {
if (_isLoaded) return;
_isLoaded = true;