From 4fec746e90cb944206a72f02f39c38941ef17de3 Mon Sep 17 00:00:00 2001 From: morrys Date: Tue, 26 Jan 2021 14:16:59 +0100 Subject: [PATCH] change busy property & refactor finalize --- packages/offline-first/src/index.ts | 38 ++++++++++++++--------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/offline-first/src/index.ts b/packages/offline-first/src/index.ts index 85c0905..62995c4 100644 --- a/packages/offline-first/src/index.ts +++ b/packages/offline-first/src/index.ts @@ -45,7 +45,7 @@ const defaultOfflineOptions = { export class OfflineFirst { private offlineStore: ICache; - private busy = false; + private busy: Promise | undefined; private offlineOptions: OfflineFirstOptions = defaultOfflineOptions; private online = isServer; private rehydrated = isServer; @@ -97,25 +97,25 @@ export class OfflineFirst { if (!this.promisesRestore) { this.promisesRestore = Promise.all([NetInfo.fetch(), this.offlineStore.restore()]) .then((result) => { - this.disposeListener = NetInfo.addEventListener((state) => { - const { isConnected } = state; - if (this.online !== isConnected && isConnected && !this.isManualExecution()) { - this.process(); - } - this.online = isConnected; - }); + const finalize = (): boolean => { + this.disposeListener = NetInfo.addEventListener((state) => { + const { isConnected } = state; + if (this.online !== isConnected && isConnected && !this.isManualExecution()) { + this.process(); + } + this.online = isConnected; + }); + this.notify(); + this.rehydrated = true; + return true; + }; + const { isConnected } = result[0]; this.online = isConnected; if (isConnected && !this.isManualExecution()) { - return this.process().then(() => { - this.notify(); - this.rehydrated = true; - return true; - }); + return this.process().then(finalize); } - this.notify(); - this.rehydrated = true; - return true; + return finalize(); }) .catch((error) => { this.rehydrated = false; @@ -162,11 +162,10 @@ export class OfflineFirst { public process(): Promise { if (!this.busy) { - this.busy = true; const { start, finish, onExecute } = this.offlineOptions; const listMutation: Array> = this.getListMutation(); let parallelPromises = []; - return start(listMutation).then(async (startMutations) => { + this.busy = start(listMutation).then(async (startMutations) => { try { for (const mutation of startMutations) { const processMutation = await onExecute(mutation); @@ -191,10 +190,11 @@ export class OfflineFirst { } catch (error) { return finish(this.getListMutation(), error); } finally { - this.busy = false; + this.busy = undefined; } }); } + return this.busy; } public executeMutation(offlineRecord: OfflineRecordCache): Promise {