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

Runs calculation functions over every value in the source sequence and emits the value as it is calculated

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

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

Remarks

If useInitialValue is 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. accumulatedValue is emitted after each call to accumulator.

If useInitialValue is 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 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────────o────────o─────/
      av       av       av

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

Return Value

IObservable.<TResult> if valueClass is null

Examples

Observable.range(1, 5)
    .scan(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:
    // 3
    // 6
    // 10
    // 15
    // Completed
Observable.range(1, 5)
    .aggregate(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:
    // !1
    // !12
    // !123
    // !1234
    // !12345
    // Completed
Clone this wiki locally