Bird
Raised Fist0
Angularframework~10 mins

Creating observables in Angular - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - Creating observables
Start
↓
Call new Observable()
↓
Define subscriber function
↓
Subscribe to Observable
↓
Observable emits values
↓
Subscriber receives values
↓
Complete or Error
↓
Subscription ends
This flow shows how an observable is created, subscribed to, emits values, and completes or errors out.
Execution Sample
Angular
import { Observable } from 'rxjs';

const obs = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.complete();
});

obs.subscribe(value => console.log(value));
Creates an observable that emits 'Hello' once and then completes, logging the value on subscription.
Execution Table
StepActionObservable StateSubscriber Callback CalledOutput
1Create Observable with subscriber functionNot startedNo
2Subscribe to ObservableSubscribedNo
3Observable calls subscriber.next('Hello')EmittingYes'Hello' logged
4Observable calls subscriber.complete()CompletedNo
5Subscription endsClosedNo
💡 Observable completes after emitting 'Hello', subscription ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
obsObservable object createdSubscribedEmitting 'Hello'CompletedClosed
subscriber callbackNot calledNot calledCalled with 'Hello'Not calledNo further calls
Key Moments - 3 Insights
Why doesn't the subscriber callback run when the Observable is created?
Because the subscriber function runs only when you subscribe (see Step 2 in execution_table). Creation just defines the Observable.
What happens if subscriber.complete() is not called?
The Observable stays open and can emit more values or errors later. Completion signals no more values will come (see Step 4).
Can the subscriber callback be called multiple times?
Yes, if subscriber.next() is called multiple times before complete(), the callback runs each time (Step 3 shows one emission).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the subscriber callback first run?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Check the 'Subscriber Callback Called' column in execution_table.
According to variable_tracker, what is the state of 'obs' after Step 4?
ASubscribed
BEmitting
CCompleted
DClosed
💡 Hint
Look at the 'obs' row and the 'After Step 4' column in variable_tracker.
If subscriber.complete() was removed, how would the execution_table change?
AStep 4 would show 'Completed' state
BStep 4 would be missing or show no completion
CSubscriber callback would not run at all
DSubscription would end immediately after Step 2
💡 Hint
Refer to the 'Observable State' and 'Subscription ends' in execution_table.
Concept Snapshot
Creating Observables in Angular:
- Use new Observable(subscriber => {...}) to create.
- subscriber.next(value) emits values.
- subscriber.complete() signals end.
- Subscribe with obs.subscribe(callback) to receive values.
- Observable runs subscriber function only on subscription.
Full Transcript
This lesson shows how to create an Observable in Angular using the Observable constructor. First, you define the Observable with a subscriber function that can emit values using subscriber.next and signal completion with subscriber.complete. The Observable does nothing until you subscribe to it. When subscribed, the subscriber function runs, emitting values to the subscriber callback. After completion, the subscription ends. This step-by-step trace helps beginners see when the subscriber callback runs and how the Observable state changes.

Practice

(1/5)
1. What is the main purpose of creating an observable in Angular?
easy
A. To create a new component
B. To watch and react to data or events over time
C. To style HTML elements
D. To define routes in the app

Solution

  1. Step 1: Understand observable concept

    Observables let you watch data or events and respond when they change.
  2. Step 2: Identify purpose in Angular

    Angular uses observables to handle asynchronous data streams and events.
  3. Final Answer:

    To watch and react to data or events over time -> Option B
  4. Quick Check:

    Observable purpose = watch/react data [OK]
Hint: Observables track data changes over time [OK]
Common Mistakes:
  • Confusing observables with components
  • Thinking observables style elements
  • Mixing observables with routing
2. Which of the following is the correct way to create a new observable in Angular?
easy
A. const obs = new Observable(subscriber => { subscriber.next('Hello'); });
B. const obs = Observable.create('Hello');
C. const obs = new Observable.next('Hello');
D. const obs = Observable('Hello');

Solution

  1. Step 1: Recall Observable creation syntax

    Use new Observable() with a function receiving a subscriber.
  2. Step 2: Check each option

    Only const obs = new Observable(subscriber => { subscriber.next('Hello'); }); correctly uses new Observable(subscriber => subscriber.next(...)).
  3. Final Answer:

    const obs = new Observable(subscriber => { subscriber.next('Hello'); }); -> Option A
  4. Quick Check:

    Correct syntax uses new Observable with subscriber function [OK]
Hint: Use new Observable(subscriber => ...) to create [OK]
Common Mistakes:
  • Using Observable.create which is deprecated
  • Calling next on Observable directly
  • Trying to call Observable as a function
3. What will be the output when subscribing to this observable?
const obs = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.complete(); subscriber.next(3); });
obs.subscribe(value => console.log(value));
medium
A. 1 2
B. 3
C. 1 2 3
D. No output

Solution

  1. Step 1: Analyze subscriber.next calls

    The observable sends 1, then 2, then calls complete(), then tries to send 3.
  2. Step 2: Understand complete behavior

    After complete() is called, no more values are sent, so 3 is ignored.
  3. Final Answer:

    1 2 -> Option A
  4. Quick Check:

    complete stops emissions, so output = 1 2 [OK]
Hint: complete() stops further values from emitting [OK]
Common Mistakes:
  • Expecting values after complete()
  • Ignoring complete() effect
  • Thinking all next() calls always emit
4. Identify the error in this observable creation code:
const obs = new Observable(subscriber => { subscriber.next('Hi'); subscriber.error('Oops'); subscriber.next('Bye'); });
medium
A. No error, code is correct
B. Missing subscriber.complete call
C. Observable constructor syntax is wrong
D. Calling subscriber.next after subscriber.error

Solution

  1. Step 1: Review observable error handling

    After calling subscriber.error(), the observable stops and no further next() calls run.
  2. Step 2: Check code sequence

    Here, subscriber.next('Bye') is called after error, which is invalid and ignored.
  3. Final Answer:

    Calling subscriber.next after subscriber.error -> Option D
  4. Quick Check:

    next after error is invalid [OK]
Hint: No next() calls after error() [OK]
Common Mistakes:
  • Thinking complete() is required after error()
  • Believing next() after error() runs
  • Confusing error() with complete()
5. You want to create an observable that emits numbers 1 to 3 with a delay of 1 second between each. Which code correctly achieves this behavior?
hard
A. const obs = new Observable(subscriber => { [1,2,3].forEach(n => { setTimeout(() => subscriber.next(n), 1000); }); });
B. const obs = new Observable(subscriber => { for(let n=1; n<=3; n++) { setTimeout(() => subscriber.next(n), 1000); } });
C. const obs = new Observable(subscriber => { let n=1; const interval = setInterval(() => { subscriber.next(n); if(n===3) clearInterval(interval); n++; }, 1000); });
D. const obs = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); });

Solution

  1. Step 1: Understand timing requirements

    We need to emit 1, 2, 3 spaced by 1 second each.
  2. Step 2: Analyze each option's timing

    const obs = new Observable(subscriber => { [1,2,3].forEach(n => { setTimeout(() => subscriber.next(n), 1000); }); }); emits 1,2,3 all after 1 second simultaneously.
    const obs = new Observable(subscriber => { for(let n=1; n<=3; n++) { setTimeout(() => subscriber.next(n), 1000); } }); emits all after 1 second simultaneously.
    const obs = new Observable(subscriber => { let n=1; const interval = setInterval(() => { subscriber.next(n); if(n===3) clearInterval(interval); n++; }, 1000); }); uses setInterval to emit each number every 1 second and stops after 3.
    const obs = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); }); emits all immediately without delay.
  3. Final Answer:

    const obs = new Observable(subscriber => { let n=1; const interval = setInterval(() => { subscriber.next(n); if(n===3) clearInterval(interval); n++; }, 1000); }); -> Option C
  4. Quick Check:

    setInterval with clearInterval emits spaced values [OK]
Hint: Use setInterval and clearInterval for timed emissions [OK]
Common Mistakes:
  • Using forEach with setTimeout causes all to run at once
  • Not clearing interval causing infinite emissions
  • Emitting all values immediately without delay
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard