In my Angular 2 app i have many observables and subscriptions. Ofcourse I should unsubscribe when I leave the page, but i'm trying to find out if it's possible to get the number of active subscriptions. Just for debugging info or when i forget to unsubscribe.
Is there such information available in rxjs?
Probably a bit late, but you could leverage the help of rxjs-spy
.
This solution is equivalent the proposed one, and, in my opinion, better maintainable.
I usually enable it globally in main.ts as a fire and forget strategy. You simply have to:
install rxjs-spy via your package manager
import in main.ts the reference to the create function: import { create } from 'rxjs-spy';
initialize the rxjs-spy in debug builds right after the angular initialization snippet:
if (environment.production) {
enableProdMode();
}
else {
//we enable RXjs Spy on non production bulds only
const spy = create();
// we call show for two purposes: first is to log to the console an empty snapshot so we can see that everything is working as expected, then to suppress unused variable usage (the latter is a convention on mine)
spy.show();
}
give your observables a name:
import { tag } from 'rxjs-spy/operators';
...
// This is a sample method which asks for a "Product" entity. Product and this.http is omitted as the focus is on tagging the observable
public getProductById(productId: number): Observable<Product> {
let params = new HttpParams()
.append('productId', productId.toString())
;
// we tag the returned observable with the name 'getProductById' (this is a convention on mine, you can choose whatsoever name)
return this.http.get<Product>(this.baseUrl + "api/product", { params: params }).pipe(tag("getProductById"));
}
when you need to look at rxjs state, you can simply open the console window and use rxSpy.show()
to have the current snapshot
You may use additional commands. A very detailed tutorial was Debugging with rxjs Spy (the link is dead as of 2020). Another good tutorial is Tooling with RxJS.
(I'd be very glad if somebody reading this answer manages to fix the formatting as I cannot have it properly within the list)