Skip to content

Commit b673e35

Browse files
dalvesfacebook-github-bot
authored andcommitted
Use weak hash map for react scroll view helper
Summary: This prevents us from leaking things via this static field. Changelog: [Android][Changed] Native ScrollView listeners list maintains weak references to listeners to avoid memory leaks Reviewed By: JoshuaGross Differential Revision: D29317937 fbshipit-source-id: 4daeb8b5533cccaebcb03acf3d595dfa58de7883
1 parent 5cb2deb commit b673e35

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java

+18-3
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
1515
import com.facebook.react.bridge.ReactContext;
1616
import com.facebook.react.uimanager.UIManagerHelper;
17-
import java.util.ArrayList;
18-
import java.util.List;
17+
import java.util.Collections;
18+
import java.util.Set;
19+
import java.util.WeakHashMap;
1920

2021
/** Helper class that deals with emitting Scroll Events. */
2122
public class ReactScrollViewHelper {
@@ -33,7 +34,8 @@ void onScroll(
3334
}
3435

3536
// Support global native listeners for scroll events
36-
private static List<ScrollListener> sScrollListeners = new ArrayList<>();
37+
private static Set<ScrollListener> sScrollListeners =
38+
Collections.newSetFromMap(new WeakHashMap<ScrollListener, Boolean>());
3739

3840
// If all else fails, this is the hardcoded value in OverScroller.java, in AOSP.
3941
// The default is defined here (as of this diff):
@@ -156,6 +158,19 @@ public void startScroll(int startX, int startY, int dx, int dy, int duration) {
156158
}
157159
}
158160

161+
/**
162+
* Adds a scroll listener.
163+
*
164+
* <p>Note that you must keep a reference to this scroll listener because this class only keeps a
165+
* weak reference to it (to prevent memory leaks). This means that code like <code>
166+
* addScrollListener(new ScrollListener() {...})</code> won't work, you need to do this instead:
167+
* <code>
168+
* mScrollListener = new ScrollListener() {...};
169+
* ReactScrollViewHelper.addScrollListener(mScrollListener);
170+
* </code> instead.
171+
*
172+
* @param listener
173+
*/
159174
public static void addScrollListener(ScrollListener listener) {
160175
sScrollListeners.add(listener);
161176
}

0 commit comments

Comments
 (0)