@tanstack/offline-transactions
Version:
Offline-first transaction capabilities for TanStack DB
76 lines (75 loc) • 2.39 kB
JavaScript
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
let _react_native_community_netinfo = require("@react-native-community/netinfo");
_react_native_community_netinfo = require_runtime.__toESM(_react_native_community_netinfo, 1);
let react_native = require("react-native");
// src/connectivity/ReactNativeOnlineDetector.ts
/**
* React Native online detector that uses RN APIs.
* Listens for:
* - Network connectivity changes via `@react-native-community/netinfo`
* - App state changes (foreground/background) via `AppState`
*/
var ReactNativeOnlineDetector = class {
constructor() {
this.listeners = /* @__PURE__ */ new Set();
this.netInfoUnsubscribe = null;
this.appStateSubscription = null;
this.isListening = false;
this.wasConnected = false;
this.handleAppStateChange = (nextState) => {
if (nextState === `active`) this.notifyListeners();
};
this.startListening();
}
startListening() {
if (this.isListening) return;
this.isListening = true;
this.netInfoUnsubscribe = _react_native_community_netinfo.default.addEventListener((state) => {
const isConnected = this.toConnectivityState(state);
if (isConnected && !this.wasConnected) this.notifyListeners();
this.wasConnected = isConnected;
});
this.appStateSubscription = react_native.AppState.addEventListener(`change`, this.handleAppStateChange);
}
stopListening() {
if (!this.isListening) return;
this.isListening = false;
if (this.netInfoUnsubscribe) {
this.netInfoUnsubscribe();
this.netInfoUnsubscribe = null;
}
if (this.appStateSubscription) {
this.appStateSubscription.remove();
this.appStateSubscription = null;
}
}
notifyListeners() {
for (const listener of this.listeners) try {
listener();
} catch (error) {
console.warn(`ReactNativeOnlineDetector listener error:`, error);
}
}
subscribe(callback) {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
if (this.listeners.size === 0) this.stopListening();
};
}
notifyOnline() {
this.notifyListeners();
}
isOnline() {
return this.wasConnected;
}
dispose() {
this.stopListening();
this.listeners.clear();
}
toConnectivityState(state) {
return !!state.isConnected && state.isInternetReachable !== false;
}
};
exports.ReactNativeOnlineDetector = ReactNativeOnlineDetector;
//# sourceMappingURL=ReactNativeOnlineDetector.cjs.map