Swicthmap in rxjs doesnt cancel the previous request

506 Views Asked by At

I am basically calling an API on keyup event of a textbox using switchmap. The problem that I am facing is that switchmap doesn't cancel the previous ongoing API call when a new API call is made

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {fromEvent, Observable} from "rxjs";
import {debounceTime, distinctUntilChanged, map, switchMap} from "rxjs/operators";

@Component({
  selector: 'app-debounce-component',
  templateUrl: './debounce-component.component.html',
  styleUrls: ['./debounce-component.component.css']
})
export class DebounceComponentComponent implements OnInit,AfterViewInit {

  constructor() { }
  @ViewChild('searchinput') ele:ElementRef

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    fromEvent(this.ele.nativeElement , 'keyup').pipe(
      debounceTime(1000),
      map(evt=>{

             return evt['target']['value']
      }),
      switchMap(value=>{
        console.log(value);
        return this.createObservable(value);
      }),
      distinctUntilChanged()
    ).subscribe() ;
  }

  createObservable(value):Observable<any>{

    return Observable.create(observer=>{
      fetch(`http://localhost:3000/courses/${value}`).then(res=>{
        res.json();
      }).then(body=>{
        observer.next(body);
        observer.complete();
      });
    })

  }

}
1

There are 1 best solutions below

0
Daniel B On

Even though it's now possible (it wasn't for a long time) to abort requests made with fetch, you'll still need an AbortController to do so. Fortunately for us, RxJS has implemented an operator called fromFetch that handles this for us.

Simply do

fromFetch("https://api.github.com/users?per_page=5").pipe(
  switchMap(response => {

and it should work as you want!