-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
SessionTracker.native.ts
60 lines (51 loc) · 1.89 KB
/
SessionTracker.native.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { ConsoleLogger as Logger } from '@aws-amplify/core';
import { AppState, AppStateStatus } from 'react-native';
import noop from 'lodash/noop';
import {
SessionState,
SessionStateChangeHandler,
SessionTrackerInterface,
} from './types';
const isActive = appState => appState === 'active';
const isInactive = appState =>
appState === 'inactive' || appState === 'background';
const logger = new Logger('InAppMessagingSessionTracker');
export default class SessionTracker implements SessionTrackerInterface {
private currentAppState: AppStateStatus;
private sessionStateChangeHandler: SessionStateChangeHandler;
constructor(sessionStateChangeHandler: SessionStateChangeHandler = noop) {
this.currentAppState = 'active';
this.sessionStateChangeHandler = sessionStateChangeHandler;
}
start = (): SessionState => {
AppState.addEventListener('change', this.appStateChangeHandler);
return this.getSessionState();
};
end = (): SessionState => {
AppState.removeEventListener('change', this.appStateChangeHandler);
return this.getSessionState();
};
private getSessionState = (): SessionState => {
if (isActive(this.currentAppState)) {
return 'started';
}
// consider any other app state as session ended
return 'ended';
};
private appStateChangeHandler = nextAppState => {
// if going from active to inactive
if (isActive(this.currentAppState) && isInactive(nextAppState)) {
logger.debug('App has gone to the background');
this.sessionStateChangeHandler('ended');
}
// if going from inactive to active
if (isInactive(this.currentAppState) && isActive(nextAppState)) {
logger.debug('App has come to the foreground');
this.sessionStateChangeHandler('started');
}
// otherwise do nothing but always update current state
this.currentAppState = nextAppState;
};
}