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

2

10

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?

Bracketing answered 7/5, 2020 at 17:0 Comment(1)
I am not sure of the answer, that's why I am putting the comment here, my thought, overriding methods are more native way API implementation rather than annotations. Because it is more readable and more close to statically typing. My second thought, compiling from overridden classes to byte-code would be faster than annotations extraction.Down
O
4

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

Overwind answered 3/8, 2021 at 8:52 Comment(0)
E
2

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.

Everybody answered 12/3, 2022 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.