Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add Teardown logic to an already existing Observable?

For instance, I'm currently calling unsubscribe from an Observable that is returned from Angular 2's HTTP module.

But I need to have some custom logic surrounding it.

Is it possible to add custom teardown logic to an already existing Observable, like the one returned from Angular 2's HTTP module?

Something along the lines of:

Observable.prototype.whenUnsubscribed(customTeardownLogic)
like image 814
Nick Kenens Avatar asked Aug 24 '16 05:08

Nick Kenens


1 Answers

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

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

@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 || { };
    }
}

// Somewhere else in your code you do:
let subscription = service.getHeroes().subscribe(/* do stuff here */);

// ...and later on:
subscription.unsubscribe();

If you want to add some custom tear-down logic, you could wrap the Observable returned by Angular 2 with your own:

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

            // Return a tear-down/unsubscribe function
            return () => {
                subscription.unsubscribe();
                this.myTearDownLogic();
            }
        }
     );
}
like image 116
yms Avatar answered Sep 30 '22 20:09

yms