Search code examples
swiftreactive-programmingrx-swift

Create an observable that emits all values so far


I have an Observable<Foo> that emits some values but never completes. Let’s call that source. I want to create an Observable<[Foo]> that emits all of the items that source has emitted so far, whenever source emits.

For example, if source emits a then b then c, the result must emit [a] then [a, b] then [a, b, c].

How can this be accomplished?

Any help much appreciated!


Solution

  • You can use the scan operator, where the accumulator is an array, and the closure adds on element to it on every new event.

    http://introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Scan

    However this is quite strange, and would really quickly become get really slow and crazy, if you're not careful.