RxJS:从Observable.fromPromise拆分数组结果

时间:2022-10-10 21:18:03

I'm using RxJS here and I can't seem to get over this seemingly simple issue.

我在这里使用RxJS,我似乎无法克服这个看似简单的问题。

rx.Observable
    .from([1,2,3,54,3,22,323,23,11,2])
    .distinct()
    .subscribe(function next (x) {
        console.log('Next');
        console.log(x);
    }, function error (x) {
        console.log('Error');
        console.log(x);
    }, function completed () {
        console.log('Completed');
    });

The above code spits out each array item in order as expected.

上面的代码按预期顺序吐出每个数组项。

rx.Observable
    .fromPromise(getNumbers([1,2,3,54,3,22,323,23,11,2]))
    .distinct()
    .subscribe(function next (x) {
        console.log('Next');
        console.log(x);
    }, function error (x) {
        console.log('Error');
        console.log(x);
    }, function completed () {
        console.log('Completed');
    });

function getNumbers (nums) {
    return new Promise(function (resolve, reject) {
        resolve(nums);
    });
}

Here though I only get the full array (i.e. [ 1, 2, 3, 54, 3, 22, 323, 23, 11, 2 ]). Shouldn't RxJS be breaking the result apart? I'd hope it at least had some logic for this.

虽然我只得到完整的数组(即[1,2,3,54,3,22,323,23,11,2])。 RxJS不应该破坏结果吗?我希望它至少对此有一些逻辑。

Thank you

谢谢

1 个解决方案

#1


16  

No it will not break them apart implicitly. If you want to split them use flatMap which will flatten the array:

不,它不会隐含地将它们分开。如果要拆分它们,请使用flatMap来展平数组:

 rx.Observable
    .fromPromise(getNumbers([1,2,3,54,3,22,323,23,11,2]))
    .flatMap(function(x) { return x; })
    .distinct()
    .subscribe(function next (x) {
        console.log('Next');
        console.log(x);
    }, function error (x) {
        console.log('Error');
        console.log(x);
    }, function completed () {
        console.log('Completed');
    });

#1


16  

No it will not break them apart implicitly. If you want to split them use flatMap which will flatten the array:

不,它不会隐含地将它们分开。如果要拆分它们,请使用flatMap来展平数组:

 rx.Observable
    .fromPromise(getNumbers([1,2,3,54,3,22,323,23,11,2]))
    .flatMap(function(x) { return x; })
    .distinct()
    .subscribe(function next (x) {
        console.log('Next');
        console.log(x);
    }, function error (x) {
        console.log('Error');
        console.log(x);
    }, function completed () {
        console.log('Completed');
    });