0
0
Angularframework~10 mins

Observable in component lifecycle in Angular - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Observable in component lifecycle
Component Init
Subscribe to Observable
Observable Emits Data
Update Component State
Component Renders Updated View
Component Destroy
Unsubscribe from Observable
This flow shows how a component subscribes to an Observable when it starts, updates its state when data arrives, and unsubscribes when it is destroyed.
Execution Sample
Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({ selector: 'app-demo', template: '<p>{{data}}</p>' })
export class DemoComponent implements OnInit, OnDestroy {
  data = '';
  sub!: Subscription;

  ngOnInit() {
    const obs = new Observable<string>(observer => {
      setTimeout(() => observer.next('Hello'), 0);
      setTimeout(() => observer.next('World'), 1000);
    });
    this.sub = obs.subscribe(value => this.data = value);
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
This Angular component subscribes to an Observable on init, updates displayed data on emissions, and unsubscribes on destroy.
Execution Table
StepActionObservable EmitsComponent State (data)Subscription StatusView Update
1Component initializes (ngOnInit)No'' (empty)Not subscribedInitial empty view
2Subscribe to ObservableNo'' (empty)SubscribedView still empty
3Observable emits 'Hello''Hello''Hello'SubscribedView shows 'Hello'
4After 1 second, Observable emits 'World''World''World'SubscribedView updates to 'World'
5Component is destroyed (ngOnDestroy)No'World'UnsubscribedView remains 'World'
6No further emissionsNo'World'UnsubscribedNo view changes
💡 Component destroyed and unsubscribed, no further Observable emissions affect the component.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
data'''''Hello''World''World''World'
sub (subscription)undefinedactiveactiveactiveclosedclosed
Key Moments - 3 Insights
Why do we unsubscribe in ngOnDestroy?
Unsubscribing in ngOnDestroy stops the Observable from sending data after the component is gone, preventing memory leaks. See step 5 in execution_table where subscription changes to 'Unsubscribed'.
What happens if Observable emits after component is destroyed?
After unsubscribing, emissions do not update component state or view. Step 6 shows no changes after destruction.
Why does the view update when Observable emits?
Because the subscription callback sets 'data', Angular detects this change and updates the view. See steps 3 and 4 where 'data' changes and view updates.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' after step 3?
A'Hello'
B'World'
C'' (empty string)
Dundefined
💡 Hint
Check the 'Component State (data)' column at step 3 in execution_table.
At which step does the subscription become closed?
AStep 2
BStep 5
CStep 3
DStep 6
💡 Hint
Look at the 'Subscription Status' column in execution_table and variable_tracker.
If we remove the unsubscribe call in ngOnDestroy, what would happen?
AView would not update on Observable emissions
BComponent would never receive data
CSubscription would remain active after component destruction
DComponent would crash immediately
💡 Hint
Refer to key_moments about unsubscribing and step 5 in execution_table.
Concept Snapshot
Angular components subscribe to Observables in ngOnInit to receive data.
Update component state inside subscription callback to refresh view.
Always unsubscribe in ngOnDestroy to avoid memory leaks.
Subscription status changes from active to closed on unsubscribe.
Observable emissions update component only while subscribed.
Full Transcript
This example shows an Angular component subscribing to an Observable during its initialization phase (ngOnInit). The Observable emits two values: 'Hello' immediately and 'World' after one second. Each emission updates the component's 'data' property, which Angular uses to update the view. When the component is destroyed (ngOnDestroy), it unsubscribes from the Observable to stop receiving further data and prevent memory leaks. The subscription status changes from active to closed at this point. If the Observable emits after the component is destroyed, the component state and view do not update. This lifecycle pattern ensures efficient and safe data handling in Angular components.