简体   繁体   中英

RxJS 6 - Angular 6 - Properly canceling current http request if a new one is triggered

So I know this is totally possible but I have never used RxJs any more than simple http get and subscribes. I have a service that is listening for WebSocket events, when 1 such event triggers, I make a call to an Api to load some data. If that websocket event triggers while 1 api is already in transit I want to cancel it and then restart a new api call. I am not sure if I am correctly using SwitchMap and I am lost of how to use Pipe with RxJs 6.

Is this the proper usage of SwitchMap and pipe to get my data? It seems to be working right when triggering a large amount of events, but seems to have a long delay after the last event has triggered however that may be server lag because my api server is also my websocket server.

My Component:

clients: Client[] = [];

  constructor(public statsApi: StatisticsService)
  {
    this.statsApi.OnClientUpdate.pipe(switchMap(x => { return this.statsApi.GetClients() })).subscribe(x =>
    {
      console.log(x);
      this.LoadClients(x);
    });
  }

  private LoadClients(clients:Client[] = null): void
  { 
    if (clients != null)
    { 
      this.clients = clients;
    } else
    { 
      this.statsApi.GetClients().subscribe(data =>
      {
        this.clients = data;
      });
    }
  }

  ngOnInit() 
  {
    this.LoadClients();
  }

GetClients inside of Service:

public GetClients(): Observable<Client[]>
  { 
    return this.http.get<Client[]>('http://localhost:5000/api/client');
  }

OnClientUpdate returns an Observable<number>

Your code is describing the process of sending an http request each time your OnClientUpdate observable yields. Each yield ends up selecting an observable which represents an http request. switchMap will subscribe to that http request observable and dispose of it's subscription to any prior http request observable. If that observable's subscription properly implements the disposal of the http request, switchMap will work as intended.

However, depending on how often OnClientUpdate can yield, you may want to add a debounce operation, thus preventing rapid-fire http request and cancellations.

Example - don't spam, cancel all but the latest request, and yield each latest result :

var latestHttpRequestResult =
    trigger
        .pipe(debounce(200))
        .pipe(switchMap(sendHttpRequestAsObservable));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM