"observer is deprecated in java 9. what should we use instead of it?" Code Answer


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.

By MattMcCode on May 3 2022

Answers related to “observer is deprecated in java 9. what should we use instead of it?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.