Skip to content

Commit fb946f9

Browse files
committed
Optimize getFirstOpenInfo
It was possible that multiple callers could trigger multiple disk reads if `getFirstOpenInfo` got called concurrently before the initial disk read completes.
1 parent 4ae0723 commit fb946f9

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/actions/FirstOpenActions.tsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,26 @@ const asFirstOpenInfo = asObject({
1616
type FirstOpenInfo = ReturnType<typeof asFirstOpenInfo>
1717

1818
let firstOpenInfo: FirstOpenInfo
19+
let firstLoadPromise: Promise<FirstOpenInfo> | undefined
1920

2021
/**
2122
* Returns whether this session was the first time the user opened the app.
22-
* Repeated calls will return the same result. Also sets the deviceId &
23-
* firstOpenEpoch
23+
* Repeated calls will return the same result. Initial disk read also sets the
24+
* deviceId & firstOpenEpoch if not already present.
2425
*/
2526
export const getFirstOpenInfo = async (): Promise<FirstOpenInfo> => {
27+
if (firstOpenInfo == null) {
28+
if (firstLoadPromise == null) firstLoadPromise = readFirstOpenInfoFromDisk()
29+
return await firstLoadPromise
30+
}
31+
return firstOpenInfo
32+
}
33+
34+
/**
35+
* Reads firstOpenInfo from disk and sets the deviceId & firstOpenEpoch if not
36+
* already present.
37+
*/
38+
const readFirstOpenInfoFromDisk = async (): Promise<FirstOpenInfo> => {
2639
if (firstOpenInfo == null) {
2740
let firstOpenText
2841
try {
@@ -34,7 +47,7 @@ export const getFirstOpenInfo = async (): Promise<FirstOpenInfo> => {
3447
// Not critical if we can't get the country code
3548
firstOpenInfo.countryCode = await getCountryCodeByIp().catch(() => undefined)
3649
}
37-
} catch (error: any) {
50+
} catch (error: unknown) {
3851
// Generate new values.
3952
firstOpenInfo = {
4053
countryCode: await getCountryCodeByIp(),

0 commit comments

Comments
 (0)