NetInfo: Cleaned up code and examples

Reviewed By: andreicoman11

Differential Revision: D2723578

fb-gh-sync-id: b7bb9ce69f24ff5dcf38409de92d57f53da003fa
This commit is contained in:
Konstantin Raev 2015-12-08 09:30:07 -08:00 committed by facebook-github-bot-9
parent e2c35dddba
commit c9d796fc6a
6 changed files with 220 additions and 346 deletions

View File

@ -1,158 +0,0 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
const React = require('react-native');
const {
NetInfo, // requires android.permission.ACCESS_NETWORK_STATE
Text,
View
} = React;
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const ConnectionSubscription = React.createClass({
getInitialState() {
return {
connectionHistory: [],
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionChange
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionChange
);
},
_handleConnectionChange: function(netInfo) {
var connectionHistory = this.state.connectionHistory.slice();
connectionHistory.push(netInfo);
this.setState({
connectionHistory,
});
},
render() {
return (
<Text>{JSON.stringify(this.state.connectionHistory)}</Text>
);
}
});
const ConnectionCurrent = React.createClass({
getInitialState() {
return {
netInfo: null,
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionChange
);
NetInfo.fetch().done(
(netInfo) => { this.setState({netInfo}); }
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionChange
);
},
_handleConnectionChange: function(netInfo) {
this.setState({
netInfo,
});
},
render() {
return (
<Text>{JSON.stringify(this.state.netInfo)}</Text>
);
}
});
const IsConnected = React.createClass({
getInitialState() {
return {
isConnected: null,
};
},
componentDidMount: function() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
},
componentWillUnmount: function() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
},
_handleConnectivityChange: function(isConnected) {
this.setState({
isConnected,
});
},
render() {
return (
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
);
}
});
const NetInfoExample = React.createClass({
statics: {
title: '<NetInfo>',
description: 'Monitor network status.'
},
getInitialState() {
return {
isMetered: null,
};
},
render() {
return (
<View >
<Text> Is Connected: <IsConnected /> </Text>
<Text> Current Connection Type: <ConnectionCurrent /> </Text>
<Text> Connection History: <ConnectionSubscription /> </Text>
<TouchableWithoutFeedback onPress={this.isConnectionMetered}>
<View>
<Text>Click to see if connection is metered: {this.state.isMetered}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
},
isConnectionMetered: function() {
NetInfo.isConnectionMetered((isConnectionMetered) => {
this.setState({
isMetered: isConnectionMetered ? 'Is Metered' : 'Is Not Metered',
});
});
}
});
module.exports = NetInfoExample;

View File

@ -1,147 +0,0 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
NetInfo,
Text,
View
} = React;
var ReachabilitySubscription = React.createClass({
getInitialState() {
return {
reachabilityHistory: [],
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleReachabilityChange
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleReachabilityChange
);
},
_handleReachabilityChange: function(reachability) {
var reachabilityHistory = this.state.reachabilityHistory.slice();
reachabilityHistory.push(reachability);
this.setState({
reachabilityHistory,
});
},
render() {
return (
<View>
<Text>{JSON.stringify(this.state.reachabilityHistory)}</Text>
</View>
);
}
});
var ReachabilityCurrent = React.createClass({
getInitialState() {
return {
reachability: null,
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleReachabilityChange
);
NetInfo.fetch().done(
(reachability) => { this.setState({reachability}); }
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleReachabilityChange
);
},
_handleReachabilityChange: function(reachability) {
this.setState({
reachability,
});
},
render() {
return (
<View>
<Text>{this.state.reachability}</Text>
</View>
);
}
});
var IsConnected = React.createClass({
getInitialState() {
return {
isConnected: null,
};
},
componentDidMount: function() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
},
componentWillUnmount: function() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
},
_handleConnectivityChange: function(isConnected) {
this.setState({
isConnected,
});
},
render() {
return (
<View>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
);
}
});
exports.title = 'NetInfo';
exports.description = 'Monitor network status';
exports.examples = [
{
title: 'NetInfo.isConnected',
description: 'Asynchronously load and observe connectivity',
render(): ReactElement { return <IsConnected />; }
},
{
title: 'NetInfo.reachabilityIOS',
description: 'Asynchronously load and observe iOS reachability',
render(): ReactElement { return <ReachabilityCurrent />; }
},
{
title: 'NetInfo.reachabilityIOS',
description: 'Observed updates to iOS reachability',
render(): ReactElement { return <ReachabilitySubscription />; }
},
];

View File

@ -0,0 +1,182 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
const React = require('react-native');
const {
NetInfo,
Text,
View,
TouchableWithoutFeedback,
} = React;
const ConnectionInfoSubscription = React.createClass({
getInitialState() {
return {
connectionInfoHistory: [],
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionInfoChange
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionInfoChange
);
},
_handleConnectionInfoChange: function(connectionInfo) {
const connectionInfoHistory = this.state.connectionInfoHistory.slice();
connectionInfoHistory.push(connectionInfo);
this.setState({
connectionInfoHistory,
});
},
render() {
return (
<View>
<Text>{JSON.stringify(this.state.connectionInfoHistory)}</Text>
</View>
);
}
});
const ConnectionInfoCurrent = React.createClass({
getInitialState() {
return {
connectionInfo: null,
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionInfoChange
);
NetInfo.fetch().done(
(connectionInfo) => { this.setState({connectionInfo}); }
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionInfoChange
);
},
_handleConnectionInfoChange: function(connectionInfo) {
this.setState({
connectionInfo,
});
},
render() {
return (
<View>
<Text>{this.state.connectionInfo}</Text>
</View>
);
}
});
const IsConnected = React.createClass({
getInitialState() {
return {
isConnected: null,
};
},
componentDidMount: function() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
},
componentWillUnmount: function() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
},
_handleConnectivityChange: function(isConnected) {
this.setState({
isConnected,
});
},
render() {
return (
<View>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
);
}
});
const IsConnectionExpensive = React.createClass({
getInitialState() {
return {
isConnectionExpensive: null,
};
},
_checkIfExpensive() {
NetInfo.isConnectionExpensive(
(isConnectionExpensive) => { this.setState({isConnectionExpensive}); }
);
},
render() {
return (
<View>
<TouchableWithoutFeedback onPress={this._checkIfExpensive}>
<View>
<Text>Click to see if connection is expensive:
{this.state.isConnectionExpensive === true ? 'Expensive' :
this.state.isConnectionExpensive === false ? 'Not expensive'
: 'Unknown'}
</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
});
exports.title = 'NetInfo';
exports.description = 'Monitor network status';
exports.examples = [
{
title: 'NetInfo.isConnected',
description: 'Asynchronously load and observe connectivity',
render(): ReactElement { return <IsConnected />; }
},
{
title: 'NetInfo.update',
description: 'Asynchronously load and observe connectionInfo',
render(): ReactElement { return <ConnectionInfoCurrent />; }
},
{
title: 'NetInfo.updateHistory',
description: 'Observed updates to connectionInfo',
render(): ReactElement { return <ConnectionInfoSubscription />; }
},
{
platform: 'android',
title: 'NetInfo.isConnectionExpensive (Android)',
description: 'Asycnronously check isConnectionExpensive',
render(): ReactElement { return <IsConnectionExpensive />; }
},
];

View File

@ -43,7 +43,7 @@ var APIS = [
require('./IntentAndroidExample.android'),
require('./LayoutEventsExample'),
require('./LayoutExample'),
require('./NetInfoExample.android'),
require('./NetInfoExample'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./TimerExample'),

View File

@ -68,7 +68,7 @@ var APIS = [
require('./CameraRollExample.ios'),
require('./GeolocationExample'),
require('./LayoutExample'),
require('./NetInfoExample.ios'),
require('./NetInfoExample'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),

View File

@ -11,13 +11,13 @@
*/
'use strict';
var Map = require('Map');
var NativeModules = require('NativeModules');
var Platform = require('Platform');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTNetInfo = NativeModules.NetInfo;
const Map = require('Map');
const NativeModules = require('NativeModules');
const Platform = require('Platform');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const RCTNetInfo = NativeModules.NetInfo;
var DEVICE_CONNECTIVITY_EVENT = 'networkStatusDidChange';
const DEVICE_CONNECTIVITY_EVENT = 'networkStatusDidChange';
type ChangeEventName = $Enum<{
change: string;
@ -54,24 +54,20 @@ type ConnectivityStateAndroid = $Enum<{
}>;
var _subscriptions = new Map();
const _subscriptions = new Map();
let _isConnected;
if (Platform.OS === 'ios') {
var _isConnected = function(
reachability: ReachabilityStateIOS
): bool {
return reachability !== 'none' &&
reachability !== 'unknown';
_isConnected = (reachability: ReachabilityStateIOS): bool => {
return reachability !== 'none' && reachability !== 'unknown';
};
} else if (Platform.OS === 'android') {
var _isConnected = function(
connectionType: ConnectivityStateAndroid
): bool {
_isConnected = (connectionType: ConnectivityStateAndroid) : bool => {
return connectionType !== 'NONE' && connectionType !== 'UNKNOWN';
};
}
var _isConnectedSubscriptions = new Map();
const _isConnectedSubscriptions = new Map();
/**
* NetInfo exposes info about online/offline status
@ -128,15 +124,15 @@ var _isConnectedSubscriptions = new Map();
*
* The rest ConnectivityStates are hidden by the Android API, but can be used if necessary.
*
* ### isConnectionMetered
* ### isConnectionExpensive
*
* Available on Android. Detect if the current active connection is metered or not. A network is
* classified as metered when the user is sensitive to heavy data usage on that connection due to
* monetary costs, data limitations or battery/performance issues.
*
* ```
* NetInfo.isConnectionMetered((isConnectionMetered) => {
* console.log('Connection is ' + (isConnectionMetered ? 'Metered' : 'Not Metered'));
* NetInfo.isConnectionExpensive((isConnectionExpensive) => {
* console.log('Connection is ' + (isConnectionExpensive ? 'Expensive' : 'Not Expensive'));
* });
* ```
*
@ -162,12 +158,12 @@ var _isConnectedSubscriptions = new Map();
* );
* ```
*/
var NetInfo = {
addEventListener: function (
const NetInfo = {
addEventListener(
eventName: ChangeEventName,
handler: Function
): void {
var listener = RCTDeviceEventEmitter.addListener(
const listener = RCTDeviceEventEmitter.addListener(
DEVICE_CONNECTIVITY_EVENT,
(appStateData) => {
handler(appStateData.network_info);
@ -176,11 +172,11 @@ var NetInfo = {
_subscriptions.set(handler, listener);
},
removeEventListener: function(
removeEventListener(
eventName: ChangeEventName,
handler: Function
): void {
var listener = _subscriptions.get(handler);
const listener = _subscriptions.get(handler);
if (!listener) {
return;
}
@ -188,7 +184,7 @@ var NetInfo = {
_subscriptions.delete(handler);
},
fetch: function(): Promise {
fetch(): Promise {
return new Promise((resolve, reject) => {
RCTNetInfo.getCurrentConnectivity(
function(resp) {
@ -200,11 +196,11 @@ var NetInfo = {
},
isConnected: {
addEventListener: function (
addEventListener(
eventName: ChangeEventName,
handler: Function
): void {
var listener = (connection) => {
const listener = (connection) => {
handler(_isConnected(connection));
};
_isConnectedSubscriptions.set(handler, listener);
@ -214,11 +210,11 @@ var NetInfo = {
);
},
removeEventListener: function(
removeEventListener(
eventName: ChangeEventName,
handler: Function
): void {
var listener = _isConnectedSubscriptions.get(handler);
const listener = _isConnectedSubscriptions.get(handler);
NetInfo.removeEventListener(
eventName,
listener
@ -226,22 +222,23 @@ var NetInfo = {
_isConnectedSubscriptions.delete(handler);
},
fetch: function(): Promise {
fetch(): Promise {
return NetInfo.fetch().then(
(connection) => _isConnected(connection)
);
},
},
isConnectionMetered: ({}: {} | (callback:Function) => void),
};
isConnectionExpensive(callback: (metered: ?boolean, error: string) => void): void {
if (Platform.OS === 'android') {
NetInfo.isConnectionMetered = function(callback): void {
RCTNetInfo.isConnectionMetered((_isMetered) => {
callback(_isMetered);
});
};
} else {
// TODO t9296080 consider polyfill and more features later on
callback(null, "Unsupported");
}
},
};
module.exports = NetInfo;