@@ -31,6 +31,8 @@ public class RNSensor extends ReactContextBaseJavaModule implements SensorEventL
31
31
private float [] orientation = new float [3 ];
32
32
private float [] quaternion = new float [4 ];
33
33
34
+ private Boolean isBeingObserved = false ;
35
+
34
36
public RNSensor (ReactApplicationContext reactContext , String sensorName , int sensorType ) {
35
37
super (reactContext );
36
38
this .reactContext = reactContext ;
@@ -94,6 +96,10 @@ private void sendEvent(String eventName, @Nullable WritableMap params) {
94
96
95
97
@ Override
96
98
public void onSensorChanged (SensorEvent sensorEvent ) {
99
+ if (!isBeingObserved ) {
100
+ return ; // avoid all the computation if there are no observers
101
+ }
102
+
97
103
int currentType = sensorEvent .sensor .getType ();
98
104
if (currentType != this .sensorType ) { // not for the current Sensor
99
105
return ;
@@ -148,4 +154,19 @@ public void onSensorChanged(SensorEvent sensorEvent) {
148
154
@ Override
149
155
public void onAccuracyChanged (Sensor sensor , int accuracy ) {
150
156
}
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
+ }
151
172
}
0 commit comments