1 1
import Observable, { ZenObservable } from 'zen-observable-ts';
2 1
import { ConsoleLogger as Logger } from '@aws-amplify/core';
3 1
import { ReachabilityMonitor } from './datastoreReachability';
4

5 1
const logger = new Logger('DataStore');
6

7 1
const RECONNECTING_IN = 5000; // 5s this may be configurable in the future
8

9
type ConnectionStatus = {
10
	// Might add other params in the future
11
	online: boolean;
12
};
13

14 1
export default class DataStoreConnectivity {
15
	private connectionStatus: ConnectionStatus;
16
	private observer: ZenObservable.SubscriptionObserver<ConnectionStatus>;
17
	constructor() {
18 0
		this.connectionStatus = {
19
			online: false,
20
		};
21
	}
22

23 1
	status(): Observable<ConnectionStatus> {
24 1
		if (this.observer) {
25 0
			throw new Error('Subscriber already exists');
26
		}
27 0
		return new Observable(observer => {
28 0
			this.observer = observer;
29
			// Will be used to forward socket connection changes, enhancing Reachability
30

31 0
			const subs = ReachabilityMonitor.subscribe(({ online }) => {
32 0
				this.connectionStatus.online = online;
33

34 0
				const observerResult = { ...this.connectionStatus }; // copyOf status
35

36 0
				observer.next(observerResult);
37
			});
38

39 0
			return () => {
40 0
				subs.unsubscribe();
41
			};
42
		});
43
	}
44

45 1
	socketDisconnected() {
46 1
		if (this.observer && typeof this.observer.next === 'function') {
47 0
			this.observer.next({ online: false }); // Notify network issue from the socket
48

49 0
			setTimeout(() => {
50 0
				const observerResult = { ...this.connectionStatus }; // copyOf status
51 0
				this.observer.next(observerResult);
52
			}, RECONNECTING_IN); // giving time for socket cleanup and network status stabilization
53
		}
54
	}
55 1
}

Read our documentation on viewing source code .

Loading