I've heard from various ng-speakers how $watch is dangerous for performance of your application. I was wondering if anyone has compared performance of Rxjs' Observable against $watch in an AngularJS application. I know that Observables is going to be part of Angular 2.
RxJS introduces Observables, a new Push system for JavaScript. An Observable is a Producer of multiple values, "pushing" them to Observers (Consumers). A Function is a lazily evaluated computation that synchronously returns a single value on invocation.
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.
The two mechanisms of observing changes are inherently different.
$watch
is a brute force, pull-based mechanism. Where the observer is active and (generally) needs to visit each observed object / expression after any change happened. Surely the more to observe the slower the whole process.
Observable
implements a push-based mechanism. Observer is passive and gets notified when something changed. Properly implemented it allows much more intelligent propagation of changes.
From what I know, using Observable
s in angular 2.0 is optional, but advised. Moreover, angular 2.0 is going to implement one-directional data flow similar to flux. Data changes propagate only downwards in DOM -- a component can directly observe / depend on data of their ancestors but not their descendants. After a change there is a guarantee that only some subtree of DOM needs update. In most cases this subtree will be much smaller than the whole DOM.
There is a great video from 2015 ng-conf benchmarking angular 1.x, react and angular 2.0. (not sure if it uses Observables though)
One last thing about Observable
: it offers way more than the above description and it is a great way of dealing with asynchronous events.
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