From f64f70c6869c1d87b0c90addce414b309e8ad35d Mon Sep 17 00:00:00 2001 From: Ldoppea Date: Wed, 4 Dec 2024 16:14:51 +0100 Subject: [PATCH] feat: Add cache for NetService state With previous implementation, NetService would do reachability tests too often and sometimes multiple times in parallel (as we can call `isOnline` from multiple parallel `client.query()` calls) This is problematic as it can unnecessary slow down the app processes This commit caches the isOnline result and register to the `NetInfo` event listener so stay up-to-date, so we can drastically reduce reachability tests on Cozy's servers --- src/pouchdb/platformReactNative.isOnline.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/pouchdb/platformReactNative.isOnline.ts b/src/pouchdb/platformReactNative.isOnline.ts index 8081dad3c..ebe669f0f 100644 --- a/src/pouchdb/platformReactNative.isOnline.ts +++ b/src/pouchdb/platformReactNative.isOnline.ts @@ -1,5 +1,15 @@ +import NetInfo from '@react-native-community/netinfo' + import { NetService } from '/libs/services/NetService' +let currentState: boolean | undefined = undefined + export const isOnline = async (): Promise => { - return (await NetService.isConnected()) ?? true + if (currentState === undefined) { + currentState = (await NetService.isConnected()) ?? true + NetInfo.addEventListener(state => { + currentState = state.isConnected ?? true + }) + } + return currentState }