Javascript 将数组序列化为元素,使用RxJS进行转换,然后将元素组装回数组

Javascript 将数组序列化为元素,使用RxJS进行转换,然后将元素组装回数组,javascript,arrays,angular,rxjs,rxjs5,Javascript,Arrays,Angular,Rxjs,Rxjs5,在Angular2中,我有许多可观察的(可观察的发射数组),它们在http.get()中产生,或者通过websocket操作馈送,因此不.complete()而是随时间发射多个值 通常,我需要使用RxJS操作符转换数组中的元素(我不想使用array.prototype.*transforms!),然后将单个元素组装回数组,数组作为单个实体发出 但我不知道如何将元素组装回数组 例如: const n$ = new Subject(); const output = n$ // creat

在Angular2中,我有许多
可观察的
(可观察的发射数组),它们在
http.get()
中产生,或者通过websocket操作馈送,因此不.complete()而是随时间发射多个值

通常,我需要使用RxJS操作符转换数组中的元素(我不想使用array.prototype.*transforms!),然后将单个元素组装回数组,数组作为单个实体发出

但我不知道如何将元素组装回数组

例如:

const n$ = new Subject();

const output = n$
    // create an observable emitting the individual elements
    // of the array
    .mergeMap(n => n)

    // some kind of transform on the elements
    .distinct((n1, n2) => n1 == n2)
    .map(n => n*n)

    // how to assemble back to an array here???
    // not working:
    // .buffer(n$)
    // also not working (subject does not complete!)
    // .toArray()

output.subscribe(v => console.log(v))

n$.next([1,1,1,2,3]);
n$.next([4,5,5,6]);

// Wanted output:
// [1, 4, 9]
// [16, 25, 36]

如果您有多个值并且想要一个值(数组),
reduce
toArray
应该是您想要的:

Rx.Observable.from([0, 1, 1, 2, 3])
    .distinct()
    .map((n) => n * n)
    // .reduce((acc, n) => { acc.push(n); return acc; }, [])
    .toArray()
    .subscribe((a) => { console.log(a); })
如果您有一个
可观察的
,只需将其放入一个
合并映射中

const output = n$
    .mergeMap((a) => Rx.Observable.from(a)
        .distinct()
        .map((n) => n * n)
        // .reduce((acc, n) => { acc.push(n); return acc; }, [])
        .toArray()
    )
    .subscribe(a => { console.log(a); });

您完全忽略了我的要点:我的示例中的主题不完整,因此您需要reduce()中的某种停止标准。您的示例使用Rx.Observable.from()完成—在本例中,
。toArray()
也可以。不,我确实看到了。除非我完全弄错了——这是可能的第二个代码段应该是开放式的-只有内部可观察到的才是完整的-在这种情况下,您是对的:对内部可观察到的使用
toArray
。您是对的,第二个代码段适用于开放式可观察到的,我很抱歉!仅供参考:.distinct()函数有一个强制的第一个参数,该参数必须是选择器函数;正如我最初在示例中所说的那样使用它是有效的。