Can I add Teardown logic to an existing Observable?

For example, I am currently triggering an unsubscribe from an Observable that is being returned from Angular 2 HTTP.

But I have the habitual logic surrounding it.

Is it possible to add custom tracking logic to an existing Observable, for example, returned from Angular 2 HTTP?

Something like the Observable.prototype.whenUnsubscribed (customTeardownLogic) lines maybe?

+4
source share
2 answers

This may not be exactly what you want, but it may help:

Suppose you have something like this (taken from the Hero Guide on the Angular 2 website):

(Typescript)

@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';  // URL to web API
  constructor (private http: Http) {}
  getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }
}

// And somewhere else in your code you do:

let subscription = service.getHeroes().subscribe( ... do stuff here );

// And later on you do:

subscription.unsubscribe();

- , Observable, Angular 2, :

getHeroes(): Observable<Hero[]> {
    return Observable.create(
        //Let provide a subscribe function
        (observer: any) => { 
            const subscription = this.http.get(this.heroesUrl)
                        .map(this.extractData).subscribe(observer);

            // Now let return a tear-down/unsubscribe function
            return () => {
                subscription.unsubscribe();
                this.myTearDownLogic();
            }
        }
     );
+2

, , .

( ) , , .

, add():

anyObservable.subscribe(function() {

  // my observer code

}).add(function() {

  // my teardown logic

});

, , , (/).

, , , .

+2

Source: https://habr.com/ru/post/1652277/


All Articles