Consider an Angular component that subscribes to an Observable but never unsubscribes. What is the most likely outcome?
import { Component, OnInit } from '@angular/core'; import { interval } from 'rxjs'; @Component({ selector: 'app-timer', template: `<p>Timer running</p>` }) export class TimerComponent implements OnInit { ngOnInit() { interval(1000).subscribe(val => console.log(val)); } }
Think about what happens to subscriptions when components are removed from the DOM.
If you don't unsubscribe from an Observable, it keeps running in the background even if the component is gone. This causes memory leaks because resources are not freed.
Choose the code that properly unsubscribes from a subscription when the component is destroyed.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription, interval } from 'rxjs'; @Component({ selector: 'app-example', template: `<p>Example</p>` }) export class ExampleComponent implements OnInit, OnDestroy { private sub?: Subscription; ngOnInit() { this.sub = interval(1000).subscribe(); } ngOnDestroy() { // Unsubscribe here } }
Look for the method that stops the subscription safely.
The unsubscribe() method stops the subscription and frees resources. Setting to null or calling non-existent methods won't unsubscribe.
Examine the code below. Why does it cause a memory leak?
import { Component, OnInit } from '@angular/core'; import { interval } from 'rxjs'; @Component({ selector: 'app-leaky', template: `<p>Leaky Component</p>` }) export class LeakyComponent implements OnInit { ngOnInit() { interval(1000).subscribe(val => console.log(val)); } }
Think about how to stop an Observable subscription.
The subscription is anonymous and not saved to a variable, so it cannot be unsubscribed. This causes the Observable to keep running indefinitely.
You have multiple subscriptions in a component. Which approach best avoids memory leaks?
Think about managing multiple subscriptions efficiently.
Grouping subscriptions in a Subscription object and unsubscribing once is efficient and reduces errors. Angular does not auto-unsubscribe.
Consider this Angular component. What will be logged to the console after the component is destroyed?
import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-test', template: `<p>Test Component</p>` }) export class TestComponent implements OnInit, OnDestroy { private sub: Subscription = new Subscription(); ngOnInit() { const sub1 = interval(500).subscribe(val => console.log('A', val)); const sub2 = interval(700).subscribe(val => console.log('B', val)); this.sub.add(sub1); this.sub.add(sub2); } ngOnDestroy() { this.sub.unsubscribe(); } }
Consider what happens when you unsubscribe a Subscription that contains multiple subscriptions.
Unsubscribing the parent Subscription stops all child subscriptions, so no logs appear after destruction.