Open History to see the last commit
1import NetInfo from '@react-native-community/netinfo'
2import { AppState } from 'react-native'
3import type { AppStateStatus, NativeEventSubscription } from 'react-native'
4import type { OnlineDetector } from '../types'
5
6/**
7 * React Native online detector that uses RN APIs.
8 * Listens for:
9 * - Network connectivity changes via `@react-native-community/netinfo`
10 * - App state changes (foreground/background) via `AppState`
11 */
12export class ReactNativeOnlineDetector implements OnlineDetector {
13 private listeners: Set<() => void> = new Set()
14 private netInfoUnsubscribe: (() => void) | null = null
15 private appStateSubscription: NativeEventSubscription | null = null
16 private isListening = false
17 private wasConnected = false
18
19 constructor() {
20 this.startListening()
21 }
22
23 private startListening(): void {
24 if (this.isListening) {
25 return
26 }
27
28 this.isListening = true
29
30 // Subscribe to network state changes
31 this.netInfoUnsubscribe = NetInfo.addEventListener((state) => {
32 const isConnected = this.toConnectivityState(state)
33
34 // Only notify when transitioning to online
35 if (isConnected && !this.wasConnected) {
36 this.notifyListeners()
37 }
38
39 this.wasConnected = isConnected
40 })
41
42 // Subscribe to app state changes (foreground/background)
43 this.appStateSubscription = AppState.addEventListener(
44 `change`,
45 this.handleAppStateChange,
46 )
47 }
48
49 private handleAppStateChange = (nextState: AppStateStatus): void => {
50 // Notify when app becomes active (foreground)
51 if (nextState === `active`) {
52 this.notifyListeners()
53 }
54 }
55
56 private stopListening(): void {
57 if (!this.isListening) {
58 return
59 }
60
61 this.isListening = false
62
63 if (this.netInfoUnsubscribe) {
64 this.netInfoUnsubscribe()
65 this.netInfoUnsubscribe = null
66 }
67
68 if (this.appStateSubscription) {
69 this.appStateSubscription.remove()
70 this.appStateSubscription = null
71 }
72 }
73
74 private notifyListeners(): void {
75 for (const listener of this.listeners) {
76 try {
77 listener()
78 } catch (error) {
79 console.warn(`ReactNativeOnlineDetector listener error:`, error)
80 }
81 }
82 }
83
84 subscribe(callback: () => void): () => void {
85 this.listeners.add(callback)
86
87 return () => {
88 this.listeners.delete(callback)
89
90 if (this.listeners.size === 0) {
91 this.stopListening()
92 }
93 }
94 }
95
96 notifyOnline(): void {
97 this.notifyListeners()
98 }
99
100 isOnline(): boolean {
101 return this.wasConnected
102 }
103
104 dispose(): void {
105 this.stopListening()
106 this.listeners.clear()
107 }
108
109 private toConnectivityState(state: {
110 isConnected: boolean | null
111 isInternetReachable: boolean | null
112 }): boolean {
113 return !!state.isConnected && state.isInternetReachable !== false
114 }
115}