I have list of observables. My target is to fire (subscribe) them with interval of one second. I have tried many options like RxJs forkJoin
, but subscriptions are fired at same time, or using RxJs concat
- but in this case thay are fired one after another completes. Also tried to loop the list with setTimeout
, but it didn't worked as well. How is that possible? I am using Angular v7 and RxJs
Example:
const observables: Observable<any>[] = [];
for (let i = 0; i < myCustomList; i++) {
observables.push(MY_API_CALL)
}
forkJoin(observables).subscribe(() => {
this._handleSuccess();
}, err => {
this._handleError();
});
In DevTools I expect to see requests (MY_API_CALL) being fired one by another with one second interval
You can use rxjs map operator, for example switchmap if you want the canceling effect:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { forkJoin, interval, pipe, of } from 'rxjs';
import { map, switchMap, take, delay } from 'rxjs/operators';
@Component({
selector: 'get-request',
templateUrl: 'get-request.component.html',
})
export class GetRequestComponent implements OnInit {
totalAngularPackages;
constructor(private http: HttpClient) {}
ngOnInit() {
const call1 = this.http.get<any>(
'https://api.npms.io/v2/search?q=scope:angular1'
);
const call2 = this.http.get<any>(
'https://api.npms.io/v2/search?q=scope:angular2'
);
const interval1 = of(true).pipe(
delay(10000),
switchMap(() => call1)
);
const interval2 = of(true).pipe(
delay(1000),
switchMap(() => call2)
);
forkJoin([interval1, interval2]).subscribe((data) => console.log(data));
}
}
Through delay operator you can control mapping delay.