Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit 3d319fe

Browse files
fix: RN warnings about EventListeners (react-native-sensors#440)
* fix RN warning about event listeners * stop emitting events if there are no listeners on Android
1 parent 4f2cb82 commit 3d319fe

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

android/src/main/java/com/sensors/RNSensor.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ public class RNSensor extends ReactContextBaseJavaModule implements SensorEventL
3131
private float[] orientation = new float[3];
3232
private float[] quaternion = new float[4];
3333

34+
private Boolean isBeingObserved = false;
35+
3436
public RNSensor(ReactApplicationContext reactContext, String sensorName, int sensorType) {
3537
super(reactContext);
3638
this.reactContext = reactContext;
@@ -94,6 +96,10 @@ private void sendEvent(String eventName, @Nullable WritableMap params) {
9496

9597
@Override
9698
public void onSensorChanged(SensorEvent sensorEvent) {
99+
if(!isBeingObserved) {
100+
return; // avoid all the computation if there are no observers
101+
}
102+
97103
int currentType = sensorEvent.sensor.getType();
98104
if(currentType != this.sensorType) { // not for the current Sensor
99105
return;
@@ -148,4 +154,19 @@ public void onSensorChanged(SensorEvent sensorEvent) {
148154
@Override
149155
public void onAccuracyChanged(Sensor sensor, int accuracy) {
150156
}
157+
158+
// this is called by RN when the first listener is registered
159+
// not implementing this method will cause a warning on RN 0.65 onwards
160+
@ReactMethod
161+
public void addListener(String eventName) {
162+
isBeingObserved = true;
163+
}
164+
165+
// this is called by RN when the last listener is deregistered
166+
// not implementing this method will cause a warning on RN 0.65 onwards
167+
@ReactMethod
168+
public void removeListeners(Integer count) {
169+
isBeingObserved = false;
170+
stopUpdates(); // maybe only calling `stopUpdates()` is enough
171+
}
151172
}

0 commit comments

Comments
 (0)