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!
To convert from array to observable you can use Rx. Observable. from(array) . To convert from observable to array, use obs.
Creating Observableslink The following example creates an Observable to emit the string 'hi' every second to a subscriber. import { Observable } from 'rxjs'; const observable = new Observable(function subscribe(subscriber) { const id = setInterval(() => { subscriber. next('hi'); }, 1000); });
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()
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With