Search code examples
angulartypescriptrxjs

Executing RXJS Functions in Sequence Defined By Array


I am attempting to execute multiple functions consecutively by defining them in an array (specifically for an Angular APP_INITIALIZER function).

I have this array:

const obsArray = [
    myService1.init(),
    myService2.init(),
    ...
    myServiceN.init()
]

Each of these init() methods returns Observable<void>. Here's an example:

    init() : Observable<void> {
         return this.http.get(this.apiUrl)
             .pipe(
                 // do something with the response
                 switchMap(() => EMPTY)
             );
    }

The ``switchMapstatement ensures that the return type isObservable```.

I've tried this:

    const init$ : Observable<void> = forkJoin(obsArray);

But at best it executes the function but not the HTTP call inside. There is no subscribe() call since this is inside an Angular factory function assigned to the APP_INITIALIZER token.

I've also tried concatMap() with no luck.

Is there an rxjs function that will execute each of these consecutively, while waiting for the previous to complete?

I have followed this up with this question.


Solution

  • You can also put all the observables from the array into an observable, essentially converting Array<Observable<T>> to Observable<Observable<T>> and then use the higher order function concatAll:

    from(obsArray).pipe(concatAll())
    

    Here's a live demo.