UNPKG

@react-native-community/netinfo

Version:
2 lines 1.98 kB
import _objectSpread from"@babel/runtime/helpers/objectSpread";import NativeInterface from'./nativeInterface';import InternetReachability from'./internetReachability';import Utils from'./utils';var DEVICE_CONNECTIVITY_EVENT='netInfo.networkStatusDidChange';var _isSetup=false;var _nativeEventSubscription=null;var _internetReachabilitySubscription=null;var _subscriptions=new Set();var _latestState=null;function fetchCurrentState(){return Utils.currentState().then(function(state){InternetReachability.update(state);var convertedState=Utils.convertState(state);_latestState=convertedState;return convertedState;});}export function setup(){if(_isSetup){return;}_nativeEventSubscription=NativeInterface.eventEmitter.addListener(DEVICE_CONNECTIVITY_EVENT,function(state){InternetReachability.update(state);var convertedState=Utils.convertState(state);_latestState=convertedState;_subscriptions.forEach(function(handler){return handler(convertedState);});});fetchCurrentState();_internetReachabilitySubscription=InternetReachability.addSubscription(function(isInternetReachable){if(!_latestState){return;}var nextState=_objectSpread({},_latestState,{isInternetReachable:isInternetReachable});_latestState=nextState;_subscriptions.forEach(function(handler){return handler(nextState);});});_isSetup=true;}export function tearDown(){if(!_isSetup){return;}if(_nativeEventSubscription){_nativeEventSubscription.remove();}_subscriptions.clear();InternetReachability.clear();if(_internetReachabilitySubscription){_internetReachabilitySubscription();}_isSetup=false;}export function latest(){if(_latestState){return Promise.resolve(_latestState);}else{return fetchCurrentState();}}export function add(handler){_subscriptions.add(handler);if(_latestState){handler(_latestState);}else{latest().then(handler);}}export function remove(handler){_subscriptions.delete(handler);}export default{setup:setup,tearDown:tearDown,latest:latest,add:add,remove:remove}; //# sourceMappingURL=state.js.map