RxJS: Splitting an array result from Observable.fromPromise

为君一笑 提交于 2019-12-19 14:37:52

问题


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

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.

Thank you


回答1:


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

 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');
    });


来源:https://stackoverflow.com/questions/32239148/rxjs-splitting-an-array-result-from-observable-frompromise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!