Search code examples
typescriptrxjsfetchunsubscribe

cancelling fetch method within an observable


I want to cancel the fetch method when unsubscribe to the subscription of the returned observable

so why should I return ()=>controller.abort()

why this method just invoked when I unsubscribe()

createHttp(url: string) {
return new Observable((observer) => {
  const controller = new AbortController()
  const signal = controller.signal
  fetch(url, { signal })
    .then((response) => response.json())
    .then((body) => {
      observer.next(body);
      observer.complete();
    })
    .catch((error) => {
      observer.error(error);
    });
   return ()=>controller.abort()
});

}

if I just return it without the es6 function like that

 return controller.abort()

it cancel the fetch method if I just subscribe()


Solution

  • The return value of an Observable needs to be a reference to a function that the Observable can call when the subscriber unsubscribes. With return controller.abort(), you are not returning a reference to the abort function, you are calling the abort function and returning its return value. With return () => controller.abort() on the other hand, you are not calling the function, you are returning the function itself that the Observable can call on unsubscribe.

    Consider the following example:

    let sayHello = () => "Hello"
    
    function exampleOne() {
      // return reference to sayHello function.
      return sayHello;
    }
    
    // vs
    
    function exampleTwo() {
      // call sayHello function and return its value ("Hello").
      return sayHello();
    }
    

    Edit

    This edit is based on comment below.

    The following is the skeleton for creating an Observable:

    new Observable((observer) => {
      // Invoked on subscribe.
      return () => {
        // Invoked on unsubscribe.
      }
    });