sagar-viradiya / AndroidPhysicsAnimation

Sample app demonstrating android physics based animation
MIT License
138 stars 18 forks source link

Scope of `by lazy` objects #3

Open ratijas opened 3 weeks ago

ratijas commented 3 weeks ago

Hi, I followed your tutorial and found it rather nice and comprehensive.

There is, however, a bit of an issue with the lifetime of animation objects created by lazy on demand and stored indefinitely in a private val: there is no way to update the target if/when the view is recreated. For example, add navigation to the app, navigate to the second fragment, and go back ­— now SpringAnimation doesn't work, because it still targets a view that should be dead and destructed by now.

    private val springAnimationTranslationX: SpringAnimation by lazy(LazyThreadSafetyMode.NONE) {
        SpringAnimation(androidBot, DynamicAnimation.TRANSLATION_X).setSpring(springForce)
    }

    private val springAnimationTranslationY: SpringAnimation by lazy(LazyThreadSafetyMode.NONE) {
        SpringAnimation(androidBot, DynamicAnimation.TRANSLATION_Y).setSpring(springForce)
    }

I know this is meant to be a simple demo app, but IMHO it might confuse people who would copy-paste parts of the code without giving it a second thought.

ratijas commented 3 weeks ago

It can be fixed by turning those lazy val fields into regular nullable var members, initializing them at the top of onViewCreated and cleaning them up in onDestroyView.

The amount of boilerplate is slightly concerning though. Why can't we just set/reset target objects of animations? I don't see why it wouldn't by a part of DynamicAnimation API.