From 5623cde2bd9aa5e21e45253af6fc6f2d2caf78af Mon Sep 17 00:00:00 2001 From: Philip Su <39933441+fivecar@users.noreply.github.com> Date: Wed, 25 Jan 2023 11:18:21 -0800 Subject: [PATCH] fix: optimize setActiveNetworkTypes to not do anything when types haven't changed (#31) --- src/index.ts | 7 +++++++ test/index.spec.ts | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/index.ts b/src/index.ts index c4c285d..bceb03c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -652,6 +652,13 @@ export default class DownloadQueue { async setActiveNetworkTypes(types: string[]): Promise { this.verifyInitialized(); + if ( + this.activeNetworkTypes.length === types.length && + this.activeNetworkTypes.every(type => types.includes(type)) + ) { + return; + } + this.activeNetworkTypes = types; if (this.netInfoFetchState) { const state = await this.netInfoFetchState(); diff --git a/test/index.spec.ts b/test/index.spec.ts index ddb5e0a..71289dd 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -1558,6 +1558,26 @@ describe("DownloadQueue", () => { await expect(queue.setActiveNetworkTypes(["wifi"])).rejects.toThrow(); }); + + it("should do nothing when setting same active network types", async () => { + const queue = new DownloadQueue(); + + await queue.init({ + domain: "mydomain", + activeNetworkTypes: ["wifi", "ethernet"], + netInfoAddEventListener: addEventListener, + netInfoFetchState: fetch, + }); + expect(addEventListener).toHaveBeenCalledTimes(1); + expect(fetch).toHaveBeenCalledTimes(1); + + await queue.setActiveNetworkTypes(["ethernet", "wifi"]); + expect(fetch).toHaveBeenCalledTimes(1); // no change + + await queue.setActiveNetworkTypes(["ethernet", "wifi", "cellular"]); + expect(fetch).toHaveBeenCalledTimes(2); + }); + it("should update activeNetworkTypes to current conditions", async () => { const queue = new DownloadQueue(); const state = createNetState(true);