Home > database >  How to see what Observables are not completed while debugging
How to see what Observables are not completed while debugging

Time:11-05

In an Angular app you might end up having quite a few Observables and you might forget to complete them when not needed anymore. Because of that they might trigger unexpectedly leading to unexpected side effects that are difficult to debug.

Is there a way to see at any moment during debugging all the Observables that are not completed? I am thinking of a DevTools tool.

CodePudding user response:

yes, there is a memory profiler devtool. Memory -> take snapshot. do something that causes memory leaks, take another snapshot and compare them

CodePudding user response:

I don't think there's any obvious and simple way to do exactly what you're looking for.

However, since RxJS 7.3 tap() operator can handle apart from the three notification types three new event "subscribe", "unsubscribe" and "finalize" (basically the same as using finalize() operator). (the same functionality could be achieved using defer() and finalize() in RxJS versions < 7.3).

In your case you could listen to all "subscribe" and "unsubscribe" and if they're called the same number of times then you know that all subscriptions were unsubscribed either manually or the source completed/errored:

import { of, tap, delay } from 'rxjs';

let counter = 0;

const source$ = of('World')
  .pipe(
    delay(1000),
    tap({
      subscribe: () => console.log('Subscribers: ',   counter),
      finalize: () => console.log('Subscribers: ', --counter),
    }),
  );
  
source$.subscribe();
source$.subscribe();
setTimeout(() => source$.subscribe(), 500);
setTimeout(() => source$.subscribe(), 2000);

Live demo: https://stackblitz.com/edit/rxjs-oht1ex?devtoolsheight=60

If all subscribers get unsubscribed then you have to see "Subscribers: 0" in the console at the end.

Note, that tap() needs to be the last operator so the finalize handler is called after the delayed value is emitted.

  • Related