Skip to content

Clarification on Request Cancellation Behavior with RxJS Operators #370

Open
@EthanShoham

Description

@EthanShoham

Description:

Hello,

I'm currently integrating ngx-jsonapi into my Angular application and have encountered a behavior related to HTTP request cancellation that I'd like to clarify.

Context:

In standard Angular applications, when using the HttpClient in conjunction with RxJS operators like switchMap, initiating a new HTTP request will cancel any previous pending requests. This ensures that only the latest request's response is processed, which is particularly useful in scenarios like type-ahead search functionalities.

Observation:

While implementing a similar pattern with ngx-jsonapi, I noticed that when triggering multiple GET requests in quick succession (e.g., via button clicks), the previous requests do not seem to be canceled automatically. This leads to multiple active HTTP requests and potential race conditions in handling responses.

Questions:

  1. Does ngx-jsonapi support automatic cancellation of previous HTTP requests when using RxJS operators like switchMap? If not, what is the recommended approach to achieve this behavior?

  2. Is there a built-in mechanism within ngx-jsonapi to handle request cancellations, or would integrating AbortController be advisable for managing such scenarios?

  3. Are there best practices or patterns recommended when using ngx-jsonapi to ensure that only the latest request's response is processed, especially in rapid successive request scenarios?

Additional Information:

For reference, here's a simplified version of the implementation:

import { Component } from '@angular/core';
import { switchMap } from 'rxjs/operators';
import { AuthorsService } from './authors.service';

@Component({
  selector: 'app-author-search',
  template: `
    <input (input)="onSearch($event.target.value)" placeholder="Search authors" />
    <ul>
      <li *ngFor="let author of authors">{{ author.attributes.name }}</li>
    </ul>
  `
})
export class AuthorSearchComponent {
  authors = [];

  constructor(private authorsService: AuthorsService) {}

  onSearch(query: string) {
    this.authorsService
      .searchAuthors(query)
      .pipe(
        switchMap(() => this.authorsService.getAuthors(query))
      )
      .subscribe(authors => {
        this.authors = authors;
      });
  }
}

In this example, each input event triggers a new search. Ideally, the previous search requests should be canceled to ensure only the latest results are processed.

I appreciate any insights or guidance you can provide on this matter.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions