How to repeat a Litho animation

175 Views Asked by At

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?

1

There are 1 best solutions below

2
Michael Osofsky On

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