Skip to content

Commit

Permalink
feat: Add cache for NetService state
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Ldoppea committed Dec 20, 2024
1 parent a1da312 commit 16d9827
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/pouchdb/platformReactNative.isOnline.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> => {
return (await NetService.isConnected()) ?? true
if (currentState === undefined) {
currentState = (await NetService.isConnected()) ?? true
NetInfo.addEventListener(state => {
currentState = state.isConnected ?? true
})
}
return currentState
}

0 comments on commit 16d9827

Please sign in to comment.