Skip to content

Commit

Permalink
Crash while using useAnimatedKeyboard in flat list (#5918)
Browse files Browse the repository at this point in the history
## Summary

Fixes #5822

To keep track of all listeners we use hash map, and notify changes on
all of them. When quickly opening flat list with components that use
useAnimatedKeyboard and focus on some keyboard, the flat list is still
adding new components (adding new listeners), while listeners are
notified in the loop about the changes to the keyboard height. Changing
HashMap to ConcurrentHashMap seems to fix the issue.

|Before|After|
|-|-|
|<video
src="https://github.com/software-mansion/react-native-reanimated/assets/11800297/66d26b5e-3e81-492b-b692-50d63bc4ca0e"
/>|<video
src="https://github.com/software-mansion/react-native-reanimated/assets/11800297/bca99310-d4e1-4cfa-a83b-de3872c93f47"
/>|

## Test plan

<details>
<summary>Test component</summary>

```jsx
import React from 'react';
import {
  FlatList,
  SafeAreaView,
  StyleSheet,
  TextInput,
  View,
} from 'react-native';

import {useAnimatedKeyboard} from 'react-native-reanimated';

function Card() {
  useAnimatedKeyboard();

  return (
    <View
      style={StyleSheet.flatten({
        width: '100%',
        height: 100,
        backgroundColor: 'black',
        marginVertical: 4,
      })}
    />
  );
}
export default function ProfileScreen() {
  const array = Array(1000).fill(0);

  const renderHeader = () => (
    <View>
      <TextInput
        numberOfLines={10}
        placeholder="text input"
        style={StyleSheet.flatten({width: '100%', height: 500, borderWidth: 2})}
      />
    </View>
  );

  return (
    <SafeAreaView style={StyleSheet.flatten({padding: 16})}>
      <FlatList
        keyboardShouldPersistTaps="always"
        data={array}
        renderItem={() => <Card />}
        ListHeaderComponent={renderHeader}
      />
    </SafeAreaView>
  );
}

```

</details>
  • Loading branch information
maciekstosio committed May 1, 2024
1 parent 1c46a97 commit 99327e6
Showing 1 changed file with 3 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.facebook.react.bridge.ReactApplicationContext;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@FunctionalInterface
interface NotifyAboutKeyboardChangeFunction {
Expand All @@ -11,7 +11,8 @@ interface NotifyAboutKeyboardChangeFunction {

public class KeyboardAnimationManager {
private int mNextListenerId = 0;
private final HashMap<Integer, KeyboardWorkletWrapper> mListeners = new HashMap<>();
private final ConcurrentHashMap<Integer, KeyboardWorkletWrapper> mListeners =
new ConcurrentHashMap<>();
private final Keyboard mKeyboard = new Keyboard();
private final WindowsInsetsManager mWindowsInsetsManager;

Expand Down

0 comments on commit 99327e6

Please sign in to comment.