Skip to content

[Android] Initialize the Handler fields eagerly - #4461

Merged
m-bert merged 1 commit into
mainfrom
@mbert/android-handler-field-init
Aug 21, 2026
Merged

[Android] Initialize the Handler fields eagerly#4461
m-bert merged 1 commit into
mainfrom
@mbert/android-handler-field-init

Conversation

@m-bert

@m-bert m-bert commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Description

Tap, LongPress, Fling, Pan and Hover gesture handlers kept their Handler as a nullable field created on first use, guarded by null checks and !! at every call site (with a TODO: lazy init left in Tap since the Kotlin conversion).

Handler object was never cleared anyway (except LongPress, where it used to serve as a flag, and Hover).

Also adds a comment explaining the 4 ms delay in HoverGestureHandler.

Test plan

  • :react-native-gesture-handler:compileDebugKotlin builds clean in basic-example
  • yarn format:android passes
Tested on the following code:
import React, { useCallback, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {
  Directions,
  GestureDetector,
  useFlingGesture,
  useHoverGesture,
  useLongPressGesture,
  usePanGesture,
  useTapGesture,
} from 'react-native-gesture-handler';
import { scheduleOnRN } from 'react-native-worklets';

type Counters = { begin: number; act: number; end: number; fail: number };
type Results = Record<string, Counters>;

const EMPTY: Counters = { begin: 0, act: 0, end: 0, fail: 0 };

export default function EmptyExample() {
  const [results, setResults] = useState<Results>({});

  const report = useCallback((key: string, kind: keyof Counters) => {
    setResults((prev) => {
      const current = prev[key] ?? EMPTY;
      return { ...prev, [key]: { ...current, [kind]: current[kind] + 1 } };
    });
  }, []);

  const tap = useTapGesture({
    onBegin: () => scheduleOnRN(report, 'tap', 'begin'),
    onActivate: () => scheduleOnRN(report, 'tap', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'tap', e.canceled ? 'fail' : 'end'),
  });

  const doubleTap = useTapGesture({
    numberOfTaps: 2,
    onBegin: () => scheduleOnRN(report, 'doubleTap', 'begin'),
    onActivate: () => scheduleOnRN(report, 'doubleTap', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'doubleTap', e.canceled ? 'fail' : 'end'),
  });

  const longPress = useLongPressGesture({
    minDurationMs: 400,
    onBegin: () => scheduleOnRN(report, 'longPress', 'begin'),
    onActivate: () => scheduleOnRN(report, 'longPress', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'longPress', e.canceled ? 'fail' : 'end'),
  });

  const fling = useFlingGesture({
    direction: Directions.RIGHT,
    onBegin: () => scheduleOnRN(report, 'fling', 'begin'),
    onActivate: () => scheduleOnRN(report, 'fling', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'fling', e.canceled ? 'fail' : 'end'),
  });

  const pan = usePanGesture({
    activateAfterLongPress: 400,
    onBegin: () => scheduleOnRN(report, 'pan', 'begin'),
    onActivate: () => scheduleOnRN(report, 'pan', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'pan', e.canceled ? 'fail' : 'end'),
  });

  const hover = useHoverGesture({
    onBegin: () => scheduleOnRN(report, 'hover', 'begin'),
    onActivate: () => scheduleOnRN(report, 'hover', 'act'),
    onFinalize: (e) =>
      scheduleOnRN(report, 'hover', e.canceled ? 'fail' : 'end'),
  });

  const rows: { key: string; label: string; gesture: any }[] = [
    { key: 'tap', label: 'Tap', gesture: tap },
    { key: 'doubleTap', label: 'DoubleTap', gesture: doubleTap },
    { key: 'longPress', label: 'LongPress 400ms', gesture: longPress },
    { key: 'fling', label: 'Fling right', gesture: fling },
    { key: 'pan', label: 'Pan holdActivate 400ms', gesture: pan },
    { key: 'hover', label: 'Hover', gesture: hover },
  ];

  return (
    <View style={styles.container}>
      {rows.map(({ key, label, gesture }) => {
        const c = results[key] ?? EMPTY;
        return (
          <GestureDetector key={key} gesture={gesture}>
            <View style={styles.box}>
              <Text style={styles.label}>{label}</Text>
              <Text style={styles.status}>
                {`${key} b:${c.begin} a:${c.act} e:${c.end} f:${c.fail}`}
              </Text>
            </View>
          </GestureDetector>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 12,
    gap: 10,
  },
  box: {
    height: 88,
    borderRadius: 12,
    backgroundColor: '#dbe4ff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  label: {
    fontSize: 18,
    fontWeight: '600',
  },
  status: {
    fontSize: 15,
    fontVariant: ['tabular-nums'],
  },
});

Copilot AI lite review requested due to automatic review settings August 21, 2026 08:14
@coderabbitai

coderabbitai Bot commented Aug 21, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ac780245-7caa-4edd-b848-1e21e644d3d8

📥 Commits

Reviewing files that changed from the base of the PR and between 592d951 and 65dcbc2.

📒 Files selected for processing (5)
  • packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/FlingGestureHandler.kt
  • packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/HoverGestureHandler.kt
  • packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/LongPressGestureHandler.kt
  • packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/PanGestureHandler.kt
  • packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/TapGestureHandler.kt

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Improved the reliability of fling, hover, long-press, pan, and tap gesture timing and callback handling on Android.
    • Ensured gesture delays and cancellations are processed consistently on the main thread.
  • Refactor
    • Simplified internal gesture scheduling and cleanup, with no changes to the public API.

Walkthrough

The Android gesture handlers now create main-looper Handler instances eagerly. Callback scheduling and cleanup no longer use nullable checks, lazy initialization, or force-unwrapping.

Changes

Gesture handler callback lifecycle

Layer / File(s) Summary
Eager Handler initialization
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/*GestureHandler.kt
Fling, hover, long-press, pan, and tap handlers now store non-null handlers initialized on the main looper.
Callback scheduling and cleanup
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/*GestureHandler.kt
Gesture start, completion, cancellation, reset, and hover transitions directly schedule or remove callbacks through the initialized handlers.

Merge Risk: ⚪ Minimal · up to 65dcb

The change eagerly initializes gesture-handler fields without any supplied evidence of a concrete correctness or production-impact risk; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: eager initialization of Handler fields on Android.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Initializes Android gesture-handler Handler instances eagerly and removes nullable access patterns, while documenting Hover’s delayed exit behavior.

Changes:

  • Eagerly initializes handlers for Tap, Pan, LongPress, Fling, and Hover.
  • Removes null checks and non-null assertions.
  • Documents the 4 ms Hover delay.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/TapGestureHandler.kt Updated as part of this pull request.
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/PanGestureHandler.kt Updated as part of this pull request.
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/LongPressGestureHandler.kt Updated as part of this pull request.
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/HoverGestureHandler.kt Updated as part of this pull request.
packages/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/core/FlingGestureHandler.kt Updated as part of this pull request.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@m-bert
m-bert requested review from j-piasecki and a lite review from Copilot August 21, 2026 08:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

@m-bert
m-bert merged commit 8a4d05d into main Aug 21, 2026
6 checks passed
@m-bert
m-bert deleted the @mbert/android-handler-field-init branch August 21, 2026 08:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants