Skip to content

Commit

Permalink
Fix sensor listener leak on Android (#3900)
Browse files Browse the repository at this point in the history
<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please follow the template so that the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes #3896

In the scenario presented in the issue every time the component was mounted two `ReanimatedSensor` were created: one was just initialized and the second one added to the hashmap. Then, when unregistering, only the second one was unregistered, the first one was kept registered. After some time the max limit of registered listeners is hit. 

## Test plan

```js
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { useAnimatedSensor, SensorType } from 'react-native-reanimated';

export function BasicLayoutAnimation() {
  return (
    <View style={styles.container}>
      <Parent />
    </View>
  );
}

const Parent = () => {
  const [state, setState] = React.useState(0);

  React.useEffect(() => {
    setInterval(() => setState((prevState) => ++prevState), 100);
  }, []);
  return (
    <View style={[styles.container, styles.parent]}>
      <Text>Parent</Text>
      <Child />
    </View>
  );
};

const Child = () => {
  useAnimatedSensor(SensorType.MAGNETIC_FIELD, {
    interval: 2000,
  });
  const count = React.useRef(0);
  React.useEffect(() => {
    console.log('render count: ', ++count.current);
  });
  return (
    <View style={styles.container}>
      <Text>Child render: {count.current}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 20,
  },
  parent: {
    backgroundColor: 'red',
  },
});

```
  • Loading branch information
graszka22 authored Jan 5, 2023
1 parent dcdad92 commit 07747fd
Showing 1 changed file with 1 addition and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public int registerSensor(
if (sensor.initialize()) {
sensorId = nextSensorId;
nextSensorId++;
sensors.put(sensorId, new ReanimatedSensor(reactContext, sensorType, interval, setter));
sensors.put(sensorId, sensor);
}
return sensorId;
}
Expand Down

0 comments on commit 07747fd

Please sign in to comment.