-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
datastoreConnectivity.ts
73 lines (60 loc) · 2.03 KB
/
datastoreConnectivity.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
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import Observable, { ZenObservable } from 'zen-observable-ts';
import { ConsoleLogger as Logger } from '@aws-amplify/core';
import { ReachabilityMonitor } from './datastoreReachability';
const logger = new Logger('DataStore');
const RECONNECTING_IN = 5000; // 5s this may be configurable in the future
type ConnectionStatus = {
// Might add other params in the future
online: boolean;
};
export default class DataStoreConnectivity {
private connectionStatus: ConnectionStatus;
private observer!: ZenObservable.SubscriptionObserver<ConnectionStatus>;
private subscription!: ZenObservable.Subscription;
private timeout!: ReturnType<typeof setTimeout>;
constructor() {
this.connectionStatus = {
online: false,
};
}
status(): Observable<ConnectionStatus> {
if (this.observer) {
throw new Error('Subscriber already exists');
}
return new Observable((observer) => {
this.observer = observer;
// Will be used to forward socket connection changes, enhancing Reachability
this.subscription = ReachabilityMonitor.subscribe(({ online }) => {
this.connectionStatus.online = online;
const observerResult = { ...this.connectionStatus }; // copyOf status
observer.next(observerResult);
});
return () => {
clearTimeout(this.timeout);
this.unsubscribe();
};
});
}
unsubscribe() {
if (this.subscription) {
clearTimeout(this.timeout);
this.subscription.unsubscribe();
}
}
// for consistency with other background processors.
async stop() {
this.unsubscribe();
return;
}
socketDisconnected() {
if (this.observer && typeof this.observer.next === 'function') {
this.observer.next({ online: false }); // Notify network issue from the socket
this.timeout = setTimeout(() => {
const observerResult = { ...this.connectionStatus }; // copyOf status
this.observer.next(observerResult);
}, RECONNECTING_IN); // giving time for socket cleanup and network status stabilization
}
}
}