简体   繁体   中英

Angular Observables return anonymous function

I have this method that I copied from a websocket tutorial but I don't understand the meaning of the "return () => { ... }" inside the observable ? Can someone explain me what is the purpose of that ?

  public onMessage(topic: string, handler = SocketClientService.jsonHandler) : Observable<any> {
    return this.connect().pipe(first(), switchMap(client => { 
      return new Observable<any>(observer => {
        const subscription : StompSubscription = client.subscribe(topic, message => {
            observer.next(handler(message));
        });
        return () => {
          console.log("Unsubscribe from socket-client service");
          client.unsubscribe(subscription .id);
        }
      });
    }));
  }

In order to create an Observable, you can use new Observable or a creation operator. See the following example:

const observable = new Observable(function subscribe(subscriber) {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
});

You can provide a function unsubscribe() to allow dispose of resources, and that function goes inside subscribe() as follows:

const observable = new Observable(function subscribe(subscriber) {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);

  return function unsubscribe() {
    console.log('Clearing resources on observable');
  };
});

Of course, you can use an arrow function expression to have:

const observable = new Observable((observer) => {
  observer.next(1);
  observer.next(2);
  observer.next(3);

  return () => {
    console.log('Clearing resources on observable');
  };
});

Try the following code to test the Observable:

const subscription = observable.subscribe(res => console.log('observable data:', res));
subscription.unsubscribe();

Finally, subscription.unsubscribe() is going to remove the socket connection in your example.

Find a project running with these examples here: https://stackblitz.com/edit/typescript-observable-unsubscribe

Let me know if that helps!

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