Search code examples
androidandroid-architecture-components

How @OnLifecycleEvent annotated methods from Architecture Components get hooked up with the LifecycleOwner?


It looks like we don't need to use kapt for @OnLifecycleEvent annotations to work. So, how do they get hooked up? Is it some kind of runtime annotation processing?

I'm asking because I'm curious what are the costs of using these annotations. Is using them affects application startup time? Or project compile time?


Solution

  • They are using reflection to find annotated functions with @OnLifecycleEvent. This is the real need why classes should implement LifecycleObserver. If there was kapt to do, that probably there shouldn't have been any interface to implement.

    The resolution is on runtime, since the retention is set to RetentionPolicy.RUNTIME.

    Reflection is expensive and therefore they are building static cache of each methods and uses the method reference, yes still reflection, to invoke each of them. I have no figures to provide how directly it affects the start up time.