RxJs Observable of vs from

RxJs Observable of vs from

Is the only difference between Observable.of and Observable.from the arguments format? Like the Function.prototype.call and Function.prototype.apply?
Observable.of(1,2,3).subscribe(() => {})
Observable.from([1,2,3]).subscribe(() => {})

Solutions/Answers:

Solution 1:

Not quite. When passing an array to Observable.from, the only difference between it and Observable.of is the way the arguments are passed.

However, Observable.from will accept an argument that is

a subscribable object, a Promise, an Observable-like, an Array, an iterable or an array-like object to be converted

There is no similar behaviour for Observable.of – which always accepts only values and performs no conversion.

Solution 2:

It is important to note the difference between of and from when passing an array-like structure (including strings):

Observable.of([1, 2, 3]).subscribe(x => console.log(x));

would print the whole array at once.

On the other hand,

Observable.from([1, 2, 3]).subscribe(x => console.log(x));

prints the elements 1 by 1.

For strings the behaviour is the same, but at character level.

Solution 3:

Another interesting fact is Observable.of([]) will be an empty array when you subscribe to it.
Where as when you subscribe to Observable.from([]) you wont get any value.

This is important when you do a consecutive saving with switchmap.
Ex:

.do((data) => {
            this.jobService.save$.next(this.job.id);
        })
        .switchMap(() => this.jobService.addSites(this.job.id, this.sites)
            .flatMap((data) => {
                if (data.length > 0) {
                    // get observables for saving
                    return Observable.forkJoin(jobSiteObservables);
                } else {
                    **return Observable.of([]);**
                }
            })).do((result) => {
            // ..
        })
        .switchMap(() => this.saveComments())
....

if data.length = 0 in addSite section, the above code is returning Observable.of([]) and then goes to save comments. But if you replace it with Observable.from([]), the succeeding methods will not get called.

rxfiddle