Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
Dmitry Ryadnenko Avatar asked Sep 24 '18 08:09

Dmitry Ryadnenko


People also ask

How do you use LifecycleOwner?

Every Activity has a Lifecycle. This Activity will be a Lifecycle Owner(any activity or fragment can be called a lifecycle owner). When an activity is initialized LifecycleOwner is the one that will be constructed initially. Any class that implements the LifeCycleOwner interface indicates that it has Android LifeCycle.

How many types of LifecycleOwner available in fragment when and which LifecycleOwner should pass?

When using a ViewModel exposing LiveData s for a Fragment , there are currently two LifecycleOwners that can be used to oberve: the Fragment itself or. the Fragment 's property mViewLifecycleOwner .

What is LifecycleOwner?

ProcessLifecycleOwner. Class that provides lifecycle for the whole application process. A class that has an Android lifecycle. These events can be used by custom components to handle lifecycle changes without implementing any code inside the Activity or the Fragment.

How can you make a class lifecycle aware in Android implement LifecycleOwner?

Step 1: Define LiveData object to store data and a method to observe that data in View class. Step 3: Define viewModel object in activity. this refers to an instance of lifecycleOwner . We are observing Data changes in activity so activity will be notified when live data has been set.


1 Answers

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.

like image 72
Nikola Despotoski Avatar answered Nov 06 '22 06:11

Nikola Despotoski