Why Observable declaration from array is not flatten?


This is a question asked in the RXJS Gitter channel but no one answers it so I post it here, hoping to have an explanation.

Hi everyone,

I am a Java developer who tries to learn rxjs. I have a dumb question about an Observable declaration. To make my life easier I told myself that working with Observable is like working with the Java Stream api (even if Stream is a pull base model). The example that disturbes me is this one: In java I have

Integer[] intArray = new Integer[] {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(intArray); // Here we have a stream of Integer not a Stream of Integer[], the array is flatten

With rxjs if I do this:

const intArray = [1, 2, 3, 4, 5]
const intObs: Observable<number> = of(intArray); // The compiler complains, I have to change Observable<number> to Observable<number[]>

It’s a bit disturbing, why the of(...) method does not flat the array?
Also, if we subscribe to an observable of Observable<number[]> why the received values are not of type number[] but of type number?
I am a bit confused. Thanks for some explanation


I don’t know anything about Java but in RxJS the generic type of Observable means what data type is this Observable going to emit (data type of each individual next emission). So Observable<number> means and Observable that emits only numbers. On the other hand Observable<number[]> means an Observable that emits arrays of numbers.

In RxJS of() only takes the value (or values) you pass as argument(s) and emits them as next emissions. It doesn’t care what data type it is, no further logic is involved (what if you do want to emit an array of values of([1, 2, 3]) and of() would keep flattenign them?).

In order to create an Observable from an array (an Observable that emits array items) you can use RxJS from() method:

from([1, 2, 3]).subscribe(...); // Will receive 3 `next` values.

Answered By – martin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published