Skip to content
richardszalay edited this page May 20, 2011 · 2 revisions

Runs calculation functions over every value in the source sequence and emits the final result. To emit the values as they are calculated, see [Scan].

static function reduce(accumulator : Function, initialValue : Object = null, 
	useInitialValue : Boolean = false) : IObservable.<TResult>

Where accumulator is function (accumulatedValue : TResult, value : T) : TResult

Remarks

If useInitialValue is not false, accumulator is called with initialValue and the first value with the return value becoming the new accumulatedValue. The new accumulatedValue is given to accumulator with the second value, and so on. The final value is emitted to the observer.

If useInitialValue is not true, accumulator is not called for the first value, instead the first value is used as the accumulatedValue for the second value.

The returned sequence completes when the source sequence completes.

The returned sequence raises an error if the source sequence raises an error, if the source sequence completes with no values, or if accumulator throws an error

Marble Diagrams

a = accumulator
av = accumulated value
xs = source
ys = output

xs ────o────────o────────o─────/
    a(av,x)  a(av,x)  a(av,x)  │
                               │
ys ────────────────────────────o/
                              av

xs ───────────────/
                  │
                  │
ys ───────────────x

Return Value

IObservable.<TResult>

Examples

Observable.range(1, 5)
    .reduce(function(av : int, x : int) : int
    {
        return av + x;
    })
    .subscribe(
        function(value : int) : void { trace(value); },
        function():void { trace("Completed"); }
    );

    // accumulator is called 4 times, starting with 1 as accumulatedValue
    // Trace output is:
    // 15
    // Completed
Observable.range(1, 5)
    .reduce(function(av : String, x : int) : String
    {
        return av + x.toString();
    }, String, "!")
    .subscribe(
        function(value : int) : void { trace(value); },
        function():void { trace("Completed"); }
    );

    // accumulator is called 5 times, starting with "!" as accumulatedValue
    // Trace output is:
    // !12345
    // Completed
Clone this wiki locally