1

The Litho animation examples all begin when a user triggers an event. But I need an animation that begins right away and continues indefinitely. In other words, I have the same problem as How to run a Litho animation automatically? but I need a solution for Litho animations as opposed to basic Android animations.

Note, I asked a related question How to run a Litho animation automatically? when I tried to modify one of Litho's examples to initiate the animation without a user event. But the question I'm asking now is how to repeat the animation once it's started?

Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113

1 Answers1

2

To start a Litho animation automatically and repeat it indefinitely, I modified RTAnimationComponentSpec by starting a TimerTask:

@OnCreateInitialState
static void createInitialState(
        ComponentContext c) {
    startRepeatingAnimation(c);
}

static void startRepeatingAnimation(final ComponentContext c) {
    Log.e(TAG, "Repeat animation handler: about to scheduleAtFixedRate");
    TimerTask animateRepeat = new java.util.TimerTask() {
        public void run() {
            try {
                Log.e(TAG, "Repeat animation handler: about to updateStateAsync");
                RTAnimationComponent.updateStateAsync(c);
            } catch (Exception e) {
                Log.e(TAG, "Repeat animation handler: exception while animating: [" + e + "]");
            }
        }
    };
    new java.util.Timer().scheduleAtFixedRate(animateRepeat, 0, FADE_IN_OUT_DURATION + FADE_IN_DELAY + FADE_IN_STAGGER_DELAY);
}

private static final String TAG = "RTComponentSpec";

I'm not sure this is a valid use of createInitialState() though. According to the documentation, it's "To set an initial value for a state". By state, Litho means variables marked @State. Informally, though, the animation is part of the state and the TimerTask does need to be started. Semantically, initializing the TimerTask seems like it belongs to creating the initial state.

Empirically, the logs showed what I wanted. The initial log message, "Repeat animation handler: about to scheduleAtFixedRate" appears once followed by periodic instances of "Repeat animation handler: about to updateStateAsync".

I suppose the solution might also work with other Android mechanisms for scheduling work on a periodic basis

Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113
  • You shouldn't start an animator in your @OnCreateInitialState method. This method is for initialising the state values, but the layout may not have been committed, so there may not be any views to animate. – Andy Oct 08 '21 at 08:40
  • A better place to start it would be in a VisibleEvent call back. e.g. https://github.com/facebook/litho/blob/master/sample/src/main/java/com/facebook/samples/litho/java/animations/animationcookbook/ContinuousExampleComponentSpec.java#L72 – Andy Oct 08 '21 at 08:43