38

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!

Paul
  • 1,897
  • 1
  • 14
  • 28

2 Answers2

43

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()
redent84
  • 18,901
  • 4
  • 62
  • 85
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
30

For future readers:

Using .merge() and .toArray() will emit a single element when all observable sequences complete. If any of the observables keeps emitting, it will not emit or complete.

Using .combineLatest() will return an Observable that emits the full list every time any observable changes:

let arrayOfObservables: [Observable<E>] = ...
let wholeSequence: Observable<[E]> = Observable.combineLatest(arrayOfObservables) { $0 }
redent84
  • 18,901
  • 4
  • 62
  • 85
  • 3
    The detail of an `Observable` completing or not makes such a big difference, thanks for pointing out. kennytm's solution will only work if your `Observables` are completing; otherwise use `combineLatest()`. – Guven Jan 21 '19 at 13:11