I have an array of http requests which uploads big files.
const requests = []
requests.push(HttpClient.post())
requests.push(HttpClient.post())
requests.push(HttpClient.post())
concat(...requests).subscribe()
I would like to cancel a file upload request for example, I would like to cancel the second file upload request. How can I do that?
I am using concat here because, requests should be done one after another i.e sequentially.
CodePudding user response:
You can pipe the result request, for example like this:
@Injectable()
class MyService {
private unsubscribe$ = new Subject<void>();
constructor(private http: HttpClient) {}
public doRequests() {
const requests = []
requests.push(this.http.post())
requests.push(this.http.post())
requests.push(this.http.post())
return concat(...requests).pipe(takeUntil(this.unsubscribe$)).subscribe()
}
public cancelRequests() {
this.unsubscribe$.next();
}
}
CodePudding user response:
You can create a subject that emits the index of the request you want cancelled. So that might look something like this:
const cancel$ = new Subject<number>();
const requests = Array.from(Array(3).keys()).map(
(_,i) => HttpClient.post().pipe(
takeUntil(cancel$.pipe(
filter(v => v === i)
))
)
);
concat(...requests).subscribe();
// cancel the second request.
cancel$.next(1);