Skip to content

Commit

Permalink
fix: RN warnings about EventListeners (#440)
Browse files Browse the repository at this point in the history
* fix RN warning about event listeners

* stop emitting events if there are no listeners on Android
  • Loading branch information
andresilveirah committed Nov 21, 2022
1 parent 4f2cb82 commit 3d319fe
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions android/src/main/java/com/sensors/RNSensor.java
Expand Up @@ -31,6 +31,8 @@ public class RNSensor extends ReactContextBaseJavaModule implements SensorEventL
private float[] orientation = new float[3];
private float[] quaternion = new float[4];

private Boolean isBeingObserved = false;

public RNSensor(ReactApplicationContext reactContext, String sensorName, int sensorType) {
super(reactContext);
this.reactContext = reactContext;
Expand Down Expand Up @@ -94,6 +96,10 @@ private void sendEvent(String eventName, @Nullable WritableMap params) {

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if(!isBeingObserved) {
return; // avoid all the computation if there are no observers
}

int currentType = sensorEvent.sensor.getType();
if(currentType != this.sensorType) { // not for the current Sensor
return;
Expand Down Expand Up @@ -148,4 +154,19 @@ public void onSensorChanged(SensorEvent sensorEvent) {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

// this is called by RN when the first listener is registered
// not implementing this method will cause a warning on RN 0.65 onwards
@ReactMethod
public void addListener(String eventName) {
isBeingObserved = true;
}

// this is called by RN when the last listener is deregistered
// not implementing this method will cause a warning on RN 0.65 onwards
@ReactMethod
public void removeListeners(Integer count) {
isBeingObserved = false;
stopUpdates(); // maybe only calling `stopUpdates()` is enough
}
}

0 comments on commit 3d319fe

Please sign in to comment.