Skip to content

Commit

Permalink
Use weak hash map for react scroll view helper
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dalves authored and facebook-github-bot committed Jun 25, 2021
1 parent 5cb2deb commit b673e35
Showing 1 changed file with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.UIManagerHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;

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

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

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

/**
* Adds a scroll listener.
*
* <p>Note that you must keep a reference to this scroll listener because this class only keeps a
* weak reference to it (to prevent memory leaks). This means that code like <code>
* addScrollListener(new ScrollListener() {...})</code> won't work, you need to do this instead:
* <code>
* mScrollListener = new ScrollListener() {...};
* ReactScrollViewHelper.addScrollListener(mScrollListener);
* </code> instead.
*
* @param listener
*/
public static void addScrollListener(ScrollListener listener) {
sScrollListeners.add(listener);
}
Expand Down

0 comments on commit b673e35

Please sign in to comment.