RxJs来自vs的可观察对象

xia*_*oke 125 rxjs

Observable.ofObservable.from参数格式之间的唯一区别是什么?喜欢Function.prototype.callFunction.prototype.apply

Observable.of(1,2,3).subscribe(() => {})
Observable.from([1,2,3]).subscribe(() => {})
Run Code Online (Sandbox Code Playgroud)

Tsv*_*ski 154

重要的是要注意传递类似数组的结构(包括字符串)之间of和之间的区别from:

Observable.of([1, 2, 3]).subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)

会立刻打印整个阵列.

另一方面,

Observable.from([1, 2, 3]).subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)

逐个打印元素.

对于字符串,行为是相同的,但在字符级别.

  • @xiaoke 那么肯定是 3 个单独的排放(1,然后是 2,然后是 3)。 (2认同)

car*_*ant 93

不完全的.传递数组时Observable.from,它与Observable.of传递参数的方式之间的唯一区别.

然而,Observable.from将接受的说法

可订阅对象,Promise,类似Observable,Array,可迭代或类似数组的对象

没有类似的行为Observable.of- 它始终只接受值并且不执行转换.


Muh*_*lal 25

of将立即发出所有值

from将一一发出所有值

of with spread运算符 = from运算符


Mab*_*abd 20

一行区别:

       let fruits = ['orange','apple','banana']
Run Code Online (Sandbox Code Playgroud)

from数组中一项一项地发出项目。例如

    from(fruits).subscribe(console.log) // 'orange','apple','banana'
Run Code Online (Sandbox Code Playgroud)

of:一次发射整个数组。例如

 of(fruits).subscribe(console.log) //  ['orange','apple','banana']
Run Code Online (Sandbox Code Playgroud)

注意: of 运算符可以像from运算符和扩展运算符一样工作

 of(...fruits).subscribe(console.log) //  'orange','apple','banana'
Run Code Online (Sandbox Code Playgroud)


Jos*_*osf 13

另一个有趣的事实是Observable.of([])在订阅它时将是一个空数组.当您订阅Observable.from([])时,您将无法获得任何价值.

使用switchmap连续保存时,这很重要.例如:

.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())
....
Run Code Online (Sandbox Code Playgroud)

如果addSite部分中的data.length = 0,则上面的代码返回Observable.of([]),然后去保存注释.但是如果用Observable.from([])替换它,则不会调用后续方法.

rxfiddle


Bja*_*sen 8

from: 从数组、promise 或 iterable 创建 observable。只取一个值。对于数组、可迭代对象和字符串,所有包含的值都将作为序列发出

const values = [1, 2, 3];
from(values); // 1 ... 2 ... 3
Run Code Online (Sandbox Code Playgroud)

of: 创建具有可变数量值的可观察对象,按顺序发出值,但数组作为单个值

const values = [1, 2, 3];
of(values, 'hi', 4, 5); // [1, 2, 3] ... 'hi' ... 4 ... 5
Run Code Online (Sandbox Code Playgroud)


Udi*_*dhi 5

  1. from 以块的形式返回通知,即一一返回。例如: from("abcde") 将返回 a => b => c => d => e
  2. 返回完整通知。例如: of("abcde") 将返回 abcde。

https://stackblitz.com/edit/typescript-sckwsw?file=index.ts&devtoolsheight=100