In TypeScript, what is the main difference between any[]
and Observable<any[])>
?
What are the cons and pros of using each of them?
相关问题
- Angular RxJS mergeMap types
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
For a great overview of various types of values across space and time, both singular and plural, see A General Theory of Reactivity.
An array is an spatial iterable. In other words, it's an iterable (a list of things) which exists at one point in space, and which you can, and want to, consume right now.
An observable is a temporal iterable. In other words, it's a list of things spread out over time, which you consume one by one.
To take a concrete example, let's examine how to iterate over each of these types of lists:
Array:
This is synchronous and will execute right now.
Observable:
This is asynchronous, and will execute one element at a time, as they come in.
However, you have asked a slightly different question, which is the difference between an array and an observable of arrays (which, for sake of clarity, we should avoid calling an "array observable", since that could be misconstrued as meaning an "array of observables", which is a different thing, although certainly useful).
The difference is that, as I mentioned, an array is just a single list of values at a single point in time. An observable of arrays is a stream of arrays, each "tick" yielding a entire, new, different array.
Therefore, use an array if you just want a list of items sitting there. Of course you can mutate or transform the array, but that doesn't change the fact that at any given point in time there is just one single array.
Use an observable of arrays if you intend to continue to get new versions of the array--different versions at different points in time--and you want to "push" each new version out to different parts of your program, which in observable terminology will "subscribe" to the observable, and be notified each time it is updated.
To answer your question then:
One is an array, and the other is an observable (stream) of arrays.
The pros and cons are that if you want an array, you should use an array. If you want an observable of arrays, then you should use an observable of arrays.
Please note that although your question refers to TypeScript, the notions of arrays and observables, including observables of arrays, are essentially language-independent.
Observables are used for implementing the Observer pattern. You can subscribe this Observable and you getting asynchrounous noticed when the Observable emit data.
Observable<any[])
is Obervable which contains an array. In this case, the array can contain any type, since it is typed by any.A array is only an object, which can hold more than one value at a time.
Take a look at the rxjs docs
vs.
MDN - Arrays