Sehmus GOKCE
Sehmus GOKCE

Reputation: 45

How do I combine observable loop results to array in RxSwift?

I have a simple stream that has numbers. I want to do some mathematical operations and then collect results sequentially in an array. How can i do that ?

func test (number : Int) -> Observable<Int> {
        let obs2 = Observable<Int>.create { (obs) -> Disposable in
            obs.onNext(number + 10)
            return Disposables.create()
        }

        return obs2
    }

let obs = Observable.from([1,2,3,4]).flatMap { (item) -> Observable<Int> in
            self.test(number: item)
            }.map { (result) -> Int in
                return result
            }

//I want this: 
obs.subscribe(onNext : {[Int] in 
     ...
     ...
}

I can't combine every int to an array.

Upvotes: 3

Views: 1889

Answers (1)

tomahh
tomahh

Reputation: 13651

let arrayObservable = obs.reduce([]) { acc, element in acc + [element] }

Reduce will start with an empty array and will append each element of the stream to the array. It will then emit only one .next event, after the source obs completes, with the result of the accumulation.


Another option would be to use the buffer operator. But keep in mind that the resulting array will only contain up to a certain number of elements and that it'll also emit every timeSpan, even if source did not emit any item.

Upvotes: 4

Related Questions