@@ -22,19 +22,29 @@ TaskManager.defineTask(BACKGROUND_SYNC_TASK, async () => {
2222
2323 console . log ( "[Background Task] Initializing PowerSync" ) ;
2424
25+ // Capture the previous lastSyncedAt BEFORE init so we can detect a sync that
26+ // completes during this background task run. `lastSyncedAt` is process-scoped
27+ // (not listener-scoped) and persists across `system.init()` calls within the
28+ // same JS runtime, so on a warm start it will already be set from a prior
29+ // foreground session - gating on `Boolean(status.lastSyncedAt)` alone would
30+ // resolve immediately without waiting for this run's sync.
31+ const previousSyncAt = system . powersync . currentStatus . lastSyncedAt ;
32+
2533 await system . init ( ) ;
2634
27- // Wait for first sync to complete to download any new data
35+ // Wait for a sync to complete during THIS background task run
2836 await new Promise < void > ( ( resolve ) => {
29- console . log ( "[Background Task] Waiting for first sync to complete" ) ;
37+ console . log ( "[Background Task] Waiting for sync to complete" ) ;
3038 const unregister = system . powersync . registerListener ( {
3139 statusChanged : ( status ) => {
32- const hasSynced = Boolean ( status . lastSyncedAt ) ;
40+ const syncedThisRun =
41+ Boolean ( status . lastSyncedAt ) &&
42+ previousSyncAt ?. getTime ( ) !== status . lastSyncedAt ?. getTime ( ) ;
3343 const downloading = status . dataFlowStatus ?. downloading || false ;
3444 const uploading = status . dataFlowStatus ?. uploading || false ;
3545
36- // Resolve when all operations have been downloaded and pending transactions have been uploaded
37- if ( hasSynced && ! downloading && ! uploading ) {
46+ // Resolve when a fresh sync has completed and no transfers are in flight
47+ if ( syncedThisRun && ! downloading && ! uploading ) {
3848 console . log (
3949 "[Background Task] Download complete"
4050 ) ;
0 commit comments