Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does rxjs observable perform compare to $watch in Angularjs 1.X?

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.

like image 249
pchitre Avatar asked Apr 17 '15 21:04

pchitre


People also ask

How does RxJS Observable work?

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.

What is difference between Observable and promise in Angular?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

What is difference between Observable and promise?

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.

What is RxJS Observable in Angular?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.


1 Answers

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 Observables 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.

like image 193
artur grzesiak Avatar answered Oct 17 '22 06:10

artur grzesiak