What's the added value of using Observable over normal Array?

168 Views Asked by At

I've been using Observables in Angular in the state layer to store the app data and to share that data among the components of the app. With a belief, using observables, that data would passively update itself in the template whenever it changes, without checking it manually.

So out of curiosity, I've made the following demonstration to see the result of not using Observables: stackblitz

It turns out that the template passively updates itself by using a normal array instead of using observables.

I'm wondering, what's the added value of using observable instead of a normal array to store/share data in the angular app?

1

There are 1 best solutions below

0
George Koval. On

Use RxJS Observables when

  1. Composing multiple events together
  2. Adding Delay
  3. Clientside rate limiting
  4. Coordinating async tasks
  5. When cancellation required (although you can use abortController for modern Promises)

they're not good for

  1. simple button clicks
  2. basic forms use
  3. Hello world apps

UPD: RxJS shines when you need fine-grained control over the stream of events (adding delays, or using operators like debounceTime/ThrottleTime, etc.). If you only intent to apply some changes per event (without having control over the stream itself), then reactive approach probably not the best option. Although I feel obligated to state that you can implement the same logic (~control over stream) without reactive approach, but it would be much more error-prone and not easily scalable). In your particular hello-world app reactive approach isn't the best option (IMHO). If you want to see the power of RxJS by your own eyes, you may try to write an app with search field, where the app should wait some time before sending actual request (limiting the amount of request: they shouldn't be made for every new letter, look debounceTime for reference) and also requests shouldn't be made for the same inputs (users typed something, then changed theirs mind and returned to previous input, and all of it within the range of, suppose, 600ms. Look distinctUntilChanges). You'll see that the non-rxjs alternative is much more verbose and difficult to read (and, more importantly, scale).