Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 579
Paul Avatar asked Feb 04 '16 16:02

Paul


People also ask

How do you map an array to an observable?

To convert from array to observable you can use Rx. Observable. from(array) . To convert from observable to array, use obs.

How do you make an observable?

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); });


2 Answers

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()
like image 57
kennytm Avatar answered Oct 19 '22 04:10

kennytm


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 }
like image 39
redent84 Avatar answered Oct 19 '22 04:10

redent84