How do I create an observable of an array from an array of observables?

Paul picture Paul · Feb 4, 2016 · Viewed 18.4k times · Source

I have an array of Thing objects that I want to convert to ConvertedThing objects, using an asynchronous function that returns Observable<ConvertedThing>.

I'd like to create an Observable<[ConvertedThing]> that emits one value when all the conversions have completed.

How can this be accomplished? Any help much appreciated!

Answer

kennytm picture kennytm · Feb 4, 2016

You can use .merge() to combine the array of observables into a single observable, and then use .toArray() to get them as a list in a single event.

For RxSwift 3+ use:

let arrayOfObservables: [Observable<E>] = ...
let singleObservable: Observable<E> = Observable.from(arrayOfObservables).merge()
let wholeSequence: Observable<[E]> = singleObservable.toArray()

For previous versions:

let arrayOfObservables: [Observable<E>] = ...
let singleObservable: Observable<E> = arrayOfObservables.toObservable().merge()
let wholeSequence: Observable<[E]> = singleObservable.toArray()