Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Break infinite queueMicrotask loop when updates are triggered in mapper-run phase #4358

Merged
merged 2 commits into from
Apr 18, 2023

Conversation

kmagiera
Copy link
Member

Summary

This fixes a problem when reanimated would get stuck in an infinite update loop triggered by shared value update in useAnimatedStyle or useDerivedValue. Although we don't recommend updating shared values in these stages of the mapper loop, it was still being used by some users that way and therefore the change mapper logic we introduced in reanimated 3 introduced a regression in that behavior.

When updating shared values in mapper phase we can never guarantee the correct order of mapper execution (as it may be the case that some mappers that used the shared value has already run and others didn't). To match the behavior of reanimated 2 we enqueue an update for the next frame that will run with the updated value.

Test plan

I used the following example that updates height in useDerivedValue:

export default function App(): React.ReactElement {
  const randomWidth = useSharedValue(10);
  const randomHeight = useSharedValue(10);

  const config = {
    duration: 500,
    easing: Easing.bezierFn(0.5, 0.01, 0, 1),
  };

  const randomerWidth = useDerivedValue(() => {
    randomHeight.value = randomWidth.value * 0.5;
    return randomWidth.value * 0.5;
  });

  const style = useAnimatedStyle(() => {
    return {
      width: withTiming(randomerWidth.value, config),
      height: randomHeight.value,
    };
  });

  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
      }}>
      <Animated.View
        style={[
          { width: 100, height: 80, backgroundColor: 'black', margin: 30 },
          style,
        ]}
      />
      <Button
        title="toggle"
        onPress={() => {
          randomWidth.value = Math.random() * 350;
        }}
      />
    </View>
  );
}

When pressing "toggle" button the old version would end up blocking UI thread forever falling into an infinite loop of running microtasks. WIth this update we allow the animation to process and you should see the height and width change after each toggle press.

@tomekzaw tomekzaw changed the title Break infinite queueMIcrotask loop when updates are triggered in mapper-run phase Break infinite queueMicrotask loop when updates are triggered in mapper-run phase Apr 13, 2023
Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
Copy link
Collaborator

@tjzel tjzel left a comment

Choose a reason for hiding this comment

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

Looks good to me!

@kmagiera kmagiera added this pull request to the merge queue Apr 18, 2023
Merged via the queue into main with commit 7cdabc5 Apr 18, 2023
@kmagiera kmagiera deleted the fix-mapper-run-inifite-loop branch April 18, 2023 07:34
mstach60161 added a commit that referenced this pull request May 9, 2023
<!-- 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

In some cases when mappers trigger event and event trigger mapper, we
can end up with infinite loop. To prevent it, I added if statement that
checks if we are already running mappers.

- fixes #4405 

## Test plan

- Checked with example from this PR: #4358 
- and code that caused that bug:

```
import React from 'react';

import Animated, {
  useAnimatedRef,
  withTiming,
  useAnimatedReaction,
  scrollTo,
  useSharedValue,
  useScrollViewOffset,
  useDerivedValue,
} from 'react-native-reanimated';
import { Button, StyleSheet, Text, View } from 'react-native';

export default function ScrollViewOffsetCallScrollToExample() {
  const aref = useAnimatedRef<Animated.ScrollView>();
  const sharedValue = useSharedValue(0);
  const scrollHandler = useScrollViewOffset(aref);

  const onChangeScrollValue = () => {
    sharedValue.value = Math.random() * 5000;
  };

  const onAnimatedChangeScrollValue = () => {
    sharedValue.value = withTiming(Math.random() * 5000);
  };

  useAnimatedReaction(
    () => {
      return sharedValue.value;
    },
    (value) => {
      scrollTo(aref, 0, value, false);
    }
  );

  useDerivedValue(() => {
    console.log(sharedValue.value)
    return {};
  });

  return (
    <>
      <View style={styles.positionView}>
        <Text>Test</Text>
        <Button
          title="Scroll without animation"
          onPress={onChangeScrollValue}
        />
        <Button
          title="Scroll with animation"
          onPress={onAnimatedChangeScrollValue}
        />
      </View>
      <View style={styles.divider} />
      <View style={styles.scrollsContainer}>
        <Animated.ScrollView
          ref={aref}
          style={styles.scrollView}>
          {[...Array(100)].map((_, i) => (
            <Text key={i} style={styles.text}>
              {i}
            </Text>
          ))}
        </Animated.ScrollView>
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  positionView: {
    margin: 20,
    alignItems: 'center',
  },
  scrollsContainer: {
    flexDirection: 'row',
  },
  scrollView: {
    flex: 1,
    width: '100%',
  },
  text: {
    fontSize: 50,
    textAlign: 'center',
  },
  divider: {
    backgroundColor: 'black',
    height: 1,
  },
});

```
fluiddot pushed a commit to wordpress-mobile/react-native-reanimated that referenced this pull request Jun 5, 2023
…er-run phase (software-mansion#4358)

## Summary

This fixes a problem when reanimated would get stuck in an infinite
update loop triggered by shared value update in useAnimatedStyle or
useDerivedValue. Although we don't recommend updating shared values in
these stages of the mapper loop, it was still being used by some users
that way and therefore the change mapper logic we introduced in
reanimated 3 introduced a regression in that behavior.

When updating shared values in mapper phase we can never guarantee the
correct order of mapper execution (as it may be the case that some
mappers that used the shared value has already run and others didn't).
To match the behavior of reanimated 2 we enqueue an update for the next
frame that will run with the updated value.

## Test plan

I used the following example that updates height in useDerivedValue:
```ts

export default function App(): React.ReactElement {
  const randomWidth = useSharedValue(10);
  const randomHeight = useSharedValue(10);

  const config = {
    duration: 500,
    easing: Easing.bezierFn(0.5, 0.01, 0, 1),
  };

  const randomerWidth = useDerivedValue(() => {
    randomHeight.value = randomWidth.value * 0.5;
    return randomWidth.value * 0.5;
  });

  const style = useAnimatedStyle(() => {
    return {
      width: withTiming(randomerWidth.value, config),
      height: randomHeight.value,
    };
  });

  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
      }}>
      <Animated.View
        style={[
          { width: 100, height: 80, backgroundColor: 'black', margin: 30 },
          style,
        ]}
      />
      <Button
        title="toggle"
        onPress={() => {
          randomWidth.value = Math.random() * 350;
        }}
      />
    </View>
  );
}
```

When pressing "toggle" button the old version would end up blocking UI
thread forever falling into an infinite loop of running microtasks. WIth
this update we allow the animation to process and you should see the
height and width change after each toggle press.

---------

Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
fluiddot pushed a commit to wordpress-mobile/react-native-reanimated that referenced this pull request Jun 5, 2023
<!-- 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

In some cases when mappers trigger event and event trigger mapper, we
can end up with infinite loop. To prevent it, I added if statement that
checks if we are already running mappers.

- fixes software-mansion#4405 

## Test plan

- Checked with example from this PR: software-mansion#4358 
- and code that caused that bug:

```
import React from 'react';

import Animated, {
  useAnimatedRef,
  withTiming,
  useAnimatedReaction,
  scrollTo,
  useSharedValue,
  useScrollViewOffset,
  useDerivedValue,
} from 'react-native-reanimated';
import { Button, StyleSheet, Text, View } from 'react-native';

export default function ScrollViewOffsetCallScrollToExample() {
  const aref = useAnimatedRef<Animated.ScrollView>();
  const sharedValue = useSharedValue(0);
  const scrollHandler = useScrollViewOffset(aref);

  const onChangeScrollValue = () => {
    sharedValue.value = Math.random() * 5000;
  };

  const onAnimatedChangeScrollValue = () => {
    sharedValue.value = withTiming(Math.random() * 5000);
  };

  useAnimatedReaction(
    () => {
      return sharedValue.value;
    },
    (value) => {
      scrollTo(aref, 0, value, false);
    }
  );

  useDerivedValue(() => {
    console.log(sharedValue.value)
    return {};
  });

  return (
    <>
      <View style={styles.positionView}>
        <Text>Test</Text>
        <Button
          title="Scroll without animation"
          onPress={onChangeScrollValue}
        />
        <Button
          title="Scroll with animation"
          onPress={onAnimatedChangeScrollValue}
        />
      </View>
      <View style={styles.divider} />
      <View style={styles.scrollsContainer}>
        <Animated.ScrollView
          ref={aref}
          style={styles.scrollView}>
          {[...Array(100)].map((_, i) => (
            <Text key={i} style={styles.text}>
              {i}
            </Text>
          ))}
        </Animated.ScrollView>
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  positionView: {
    margin: 20,
    alignItems: 'center',
  },
  scrollsContainer: {
    flexDirection: 'row',
  },
  scrollView: {
    flex: 1,
    width: '100%',
  },
  text: {
    fontSize: 50,
    textAlign: 'center',
  },
  divider: {
    backgroundColor: 'black',
    height: 1,
  },
});

```
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.

4 participants