PokerJoker
PokerJoker

Reputation: 211

Angular rxjs how to call multiple same http requests like one subscription?

For example I have multiple ids : [1,2,3,4,5] and then for each id I want to call delete api endpoint.Normally I would have to call it 5 times with forEach function :

ids.forEach(item => {
this.myService.delete(item).subscribe.....

}) 

But what if I want to combine it to one observable, so I could know when the loop has ended (complete state in rxjs) ?

Can I do something like this ?

Upvotes: 2

Views: 1520

Answers (2)

Kelum Bandara
Kelum Bandara

Reputation: 478

I guess you can also do this using zip operator

deleteIds(ids: Array<number>) {
    // create a array of delete observables to be executed at once
    const deleteIds = ids.map(id => this.myService.delete(id));
    zip(...deleteIds).subscribe(() => {
        // execute the rest of the code
    });
}

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 56054

You can first create the array of observables, then use forkJoin to execute them parallely!

deleteIds(ids: Array<number>) {
    // create a array of delete observables to be executed at once
    const deleteIds = ids.map(id => this.myService.delete(id));
    forkJoin(deleteIds).subscribe(() => {
        // execute the rest of the code
    });
}

Upvotes: 3

Related Questions