Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DefaultLifecycleObserver preferred over the Lifecycle annotations when Java 8 on Android is available?

According to the Android developer documentation on Lifecycle:

If you use Java 7 Language, Lifecycle events are observed using annotations. Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between DefaultLifecycleObserver and annotations, you must always prefer DefaultLifecycleObserver.

class TestObserver implements DefaultLifecycleObserver {
     @Override
     public void onCreate(LifecycleOwner owner) {
         // your code
     }
 }

What specific Java 8 language/jvm features are driving the deprecation of the Lifecycle annotations? For example, do we get better performance (build or runtime) when using the DefaultLifecycleObserver?

like image 423
hopia Avatar asked May 07 '20 17:05

hopia


2 Answers

I think it is because DefaultLifecycleObserver uses interface default methods, which is a Java 8 feature.

like image 96
Paul Grime Avatar answered Nov 19 '22 07:11

Paul Grime


As the Documentation says:

This annotation required the usage of code generation or reflection, which should be avoided. Use DefaultLifecycleObserver or LifecycleEventObserver instead.

Should reflection be avoided?

It is generally a bad idea to use reflection in the application code because you lose the strict type checking of the language. Reflection is generally for use by framework code, where it is essential. ... If it is possible to perform an operation without using reflection, then it is preferable to avoid using it.

Final views:

It's deprecated because they now expect you to use Java 8 and implement the interface DefaultLifecycleObserver. Since Java 8 allows interfaces to have default implementations, they defined DefaultLifecycleObserver with empty implementations of all the methods so you only need to override the ones you use. The old way of marking functions with @OnLifecycleEvent was a crutch for pre-Java 8 projects. This was the only way to allow a class to selectively choose which lifecycle events it cared about. The alternative would have been to force those classes to override all the lifecycle interface methods, even if leaving them empty.

like image 26
N-RAYAN Avatar answered Nov 19 '22 08:11

N-RAYAN