What is the best practice to unsubscribe within a Angular2 service from a http subscription?
Currently I do this but I'm not sure if this will be the best way.
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { Subject } from "rxjs/Subject";
import { ISubscription } from "rxjs/Subscription";
@Injectable()
export class SearchService {
private _searchSource = new Subject<any>();
public search$ = this._searchSource.asObservable();
constructor(private _http: Http) {}
public search(value: string) {
let sub: ISubscription = this._http.get("/api/search?value=" + value)
.map(response => <any>response.json())
.do(data => this._searchSource.next(data))
.finally(() => sub.unsubscribe()).subscribe();
}
}
A Service in Angular is a singleton. This means that the service will exist for the entire lifespan of your application.
The reason that you need to unsubscribe from an observable, is to avoid memory leaks. When do you get memory leaks? If something has been garbage collected while it was still subscribed to an observable, event listener, socket, ...
Since an Angular service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it. The observable will either complete or error or keep going as long as your application does.
Conclusion: Unsubscribing in a service is kind of pointless, since there is no chance of memory leaks.