I am new to typescript and RxJs and was assigned a bug where our search often fails with HTTP 404 status.
Especially when the user runs the app from remote.

The search call is made to a backend that spins off long running searches that will have to be polled until they are done. This is done by giving a X-TaskId in the header.

I found the suspicious method below and I suspect that what this method does is polling each second regardless of how long the search call takes. I.e. there is a risk for polling a search taskId that has been completed and does not exist which will give us a 404.

The return HTTP status

* 200: When search is done in which case the response body will contain the result.
* 202: The search is running and an X-TaskId header field indicates its id.
* 404: The given search taskId does not exist.

```
  performSearch(pollingInterval: number, searchCriterias: string[], search: MalSokningDto[], actor: string): void {
    this.scrollAndFocus(searchCriterias[0]);
    this.searchSubscription = this.searchService.search(search, null).subscribe(
      (initialResponse: HttpResponse<ResponseDto>) => {
        if (initialResponse.status === 202) {
          this.taskId = initialResponse.headers.get('X-TaskId');
          interval(pollingInterval)
            .pipe(
              switchMap(() => this.searchService.search(search, this.taskId)),
              filter((response: HttpResponse<ResponseDto>) => response.status === 200),
              take(1),
              timeout(30000)
            )
            .subscribe(
              (response: HttpResponse<ResponseDto>) => {
                this.loading = false;
                this.showSearchResult(searchCriterias, response.body, actor, null);
              },
              (error: Error) => {
                this.loading = false;
                this.showSearchResult(searchCriterias, null, actor, error);
              }
            );
        }
      },
      (error: Error) => {
        this.loading = false;
        this.showSearchResult(searchCriterias, null, actor, error);
      }
    );
  }

```

I have lots of question about this code.

1. How do I (In RxJS async) style switch to refactor this to adding a wait for previous call plus a delay between server calls.
2. There is redundancy in that we have two calls to searchService.search and 3 calls to showSearchResult.
3. We store a global searchSubscription (that we later may cancel) but what about all the others that are created. (Our searches may take 10-30 seconds so there will be 20-30 calls made) I guess our cancel search does not always work either.