Can I create animations on Android with Coroutines?


#1

I understand that delay(), which is an alternative to Thread.sleep(), doesn’t block the UI thread. Does that mean I can create simple animations with it? The following code works, but is it okay to use it?

launch(UI) {    
    while(myview.alpha < 1f) {
        myview.alpha += 0.001f
        delay(200)
    }
}

#2

It’s OK to use as in it will not create blockages etc. The android infrastructure is however not expected to reliably schedule the continuation. Animation this way will be very stuttering.

A better idea of animation is often to take another approach. As long as you’re animating you invalidate the drawing as part of your onDraw. Then in your onDraw measure the time elapsed since the start of the animation. You position/adapt the elements according to this elapsed time so that even if a frame is dropped your animation is always at the right point, stutters less and automatically adapts to the framerate of the device.


#3

Take a look at this example app: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-javafx/src/test/kotlin/examples/FxExampleApp.kt

It does animations in JavaFx using coroutines. However, instead of using delay it uses JavaFx.awaitPulse to suspend coroutine until the next animation tick. I don’t know if there is a similar concept in Android, but if there is, we can add the corresponding function to kotlinx-coroutines-android module, too.


#4

Hmm. There appears to be a way to hook in to the infrastructure that is used by Animator subclases. There is a hidden AnimationHandler service used by ValueAnimators. A ValueAnimator subclass could be used to do so. To make it pretty you probably need some infrastructure to recalculate the correct values again (if you want delay dependent animation).


#5

Thanks. I’ve added UI.awaitFrame suspending function that is based on Android’s animation framework for the upcoming release of kotlinx.coroutines. There will be also an example Android application that uses coroutines for animations: https://github.com/Kotlin/kotlinx.coroutines/blob/develop/ui/kotlinx-coroutines-android/animation-app/app/src/main/java/org/jetbrains/kotlinx/animation/Animation.kt