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 preferDefaultLifecycleObserver
.
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
?
I think it is because DefaultLifecycleObserver
uses interface default methods, which is a Java 8 feature.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With