Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

Observer is deprecated in Java 9. What should we use instead of it?

Java 9 came out, and Observer has been deprecated. Why is that? Does it mean that we shouldn't implement observer pattern anymore?

It would be good to know what is a better alternative?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why is that? Does it mean that we shouldn't implement observer pattern anymore?

Answering the latter part first -

YES, it does mean you shouldn't implement Observer and Obervables anymore.

Why were they deprecated -

They didn't provide a rich enough event model for applications. For example, they could support only the notion that something has changed, but didn't convey any information about what has changed.

Alex's answer puts it nicely upfront that Observer has a weakness: all Observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.

To add to it there were bugs like one could not serialize the Observable class because as it didn't implement Serializable interface and all of its members were private.

What is a better alternative to that?

On the other hand Listeners have a lot of types and they have callback methods and don't require casting. As pointed by @Ravi in his answer you can make use of PropertyChangeListener instead.

For the rest of it the @Deprecation has been marked with proper documentation to explore other packages as linked in other answers as well.


Note that the deprecation was also marked with an analysis as stated in this mail -

These days, anyone encountering these is probably hitting them by mistake while using RxJava or other reactive-stream frameworks. In which case, users will normally want to instead use the jdk9 java.util.concurrent.Flow APIs that all reactive-streams frameworks should be compatible/interoperable within their planned upcoming jdk9-compatible versions.

Edit: It's also worth mentioning that the deprecation of the APIs is not primarily just because of the above reason, but also being unable to maintain such legacy code as mentioned in comments of a few of the bug reports (linked above) which were raised to mark an improvement in its implementation in one or another way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...