Introduction

We use RxJS in every Angular app we write, it has a large impact on the data flow across our app, performance and much more

It is important to unsubscribe from our Observables in order to avoid memory leaks. This article will show you most of the patterns you can unsubscribe from Observables in your Angular components!

We start with creating this dummy service to help up keep track on the subscriptions we are making

@Injectable({
  providedIn: 'root',
})
export class DummyService {
  getEmissions(scope: string): Observable<string> {
    return Observable.create((observer) => {
      console.log(`${scope} Subscribed`);

      const subscription: Subscription = timer(0, 1000)
        .pipe(
          map((n) => `${scope} Emission #${n}`),
          tap(console.log)
        )
        .subscribe(observer);

      return () => {
        subscription.unsubscribe();
        console.log(`${scope} Unsubscribed`);
      };
    });
  }
}

Our dummy service will have a single getEmissions method, which accepts a scope to log events and returns an Observable which emits

${scope} Emission #n every nth second.

#javascript #angular #rxjs #tutorial

RxJS & Angular - Unsubscribe Like a Pro
12.00 GEEK