What's difference between “reduce” and “scan”

前端 未结 3 1148
孤独总比滥情好
孤独总比滥情好 2021-02-12 09:21

I\'m studying RXJS and stuck with the problem: the same code with operators \"reduce\" and \"scan\" works in different ways, but I think that must return equal result. Example b

3条回答
  •  孤街浪徒
    2021-02-12 09:53

    From RxJS documentation,

    Scan

    apply a function to each item emitted by an Observable, sequentially, and emit each successive value

    Reduce

    apply a function to each item emitted by an Observable, sequentially, and emit the final value

    Example codes

    Scan

    var source = Rx.Observable.range(1, 3)
    .scan(
        function (acc, x) {
            return acc + x;
        });
    
    var subscription = source.subscribe(
        function (x) { console.log('Next: ' + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
    

    For each value emitted by the Observable, scan emits corresponding output sequentially, So the Output will have 3 values for range 1 to 3, as follows

    Output
    Next: 1
    Next: 3
    Next: 6
    Completed
    

    Reduce

    var source = Rx.Observable.range(1, 3)
        .reduce(function (acc, x) {
            return acc * x;
        }, 1)
    
    var subscription = source.subscribe(
        function (x) { console.log('Next: ' + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
    

    Reduce function reduces the values from observables to a single value (final result) and emit. So the output will be as follows,

    Next: 6
    Completed
    

提交回复
热议问题