'of' vs 'from' operator

后端 未结 7 2081
栀梦
栀梦 2020-11-29 17:18

Is the only difference between Observable.of and Observable.from the arguments format? Like the Function.prototype.call and Func

7条回答
  •  失恋的感觉
    2020-11-29 17:33

    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 operation with switchmap.

    Ex: In the below example, I am saving a job and then sites, and then comments as a stream.

    .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 there's no site to save, ie; 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

提交回复
热议问题