Bird
Raised Fist0
Angularframework~20 mins

BehaviorSubject as simple store in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
BehaviorSubject Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Angular component using BehaviorSubject?

Consider this Angular component that uses a BehaviorSubject as a simple store. What will be displayed in the template after the button is clicked once?

Angular
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count$ | async }}</p>
    <button (click)="increment()">Increment</button>
  `
})
export class CounterComponent {
  private countSubject = new BehaviorSubject<number>(0);
  count$ = this.countSubject.asObservable();

  increment() {
    const current = this.countSubject.value;
    this.countSubject.next(current + 1);
  }
}
ACount: NaN
BCount: 1
CCount: undefined
DCount: 0
Attempts:
2 left
💡 Hint

Remember that BehaviorSubject holds the current value and emits it to subscribers immediately.

state_output
intermediate
2:00remaining
What is the value of the BehaviorSubject after these operations?

Given this code snippet, what is the final value emitted by store$?

Angular
import { BehaviorSubject } from 'rxjs';

const store = new BehaviorSubject({ count: 0 });

store.next({ count: store.value.count + 1 });
store.next({ count: store.value.count + 2 });

const store$ = store.asObservable();
A{"count": 3}
B{"count": 0}
C{"count": 2}
D{"count": 1}
Attempts:
2 left
💡 Hint

Each next uses the current value at that moment.

📝 Syntax
advanced
2:00remaining
Which option correctly creates a BehaviorSubject with initial value and exposes it as observable?

Choose the correct code snippet that creates a BehaviorSubject with initial value 10 and exposes it as a read-only observable named value$.

A
private valueSubject = BehaviorSubject(10);
public value$ = valueSubject.asObservable();
B
public valueSubject = new BehaviorSubject(10);
private value$ = this.valueSubject.asObservable();
C
private valueSubject = new BehaviorSubject&lt;number&gt;(10);
public value$ = this.valueSubject.asObservable();
D
const valueSubject = new BehaviorSubject&lt;number&gt;;
const value$ = valueSubject.asObservable();
Attempts:
2 left
💡 Hint

Remember to use new keyword and specify initial value in constructor.

🔧 Debug
advanced
2:00remaining
Why does this BehaviorSubject-based store not update the component view?

In this Angular component, the template does not update when updateName is called. What is the cause?

Angular
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-name',
  template: `
    <p>Name: {{ name$ | async }}</p>
    <button (click)="updateName('Alice')">Set Alice</button>
  `
})
export class NameComponent {
  private nameSubject = new BehaviorSubject<string>('Bob');
  name$ = this.nameSubject.asObservable();

  updateName(newName: string) {
    this.nameSubject.next(newName);
  }
}
ADirectly assigning to nameSubject.value does not emit a new value; use next() instead.
BThe template is missing the async pipe, so it does not update.
CBehaviorSubject cannot hold string values; it only supports numbers.
DThe component selector is incorrect, so the component is not rendered.
Attempts:
2 left
💡 Hint

Check how to properly update a BehaviorSubject's value.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of using BehaviorSubject as a simple store in Angular?

Choose the best explanation for why BehaviorSubject is often used as a simple store in Angular applications.

AIt enforces immutability of the state, preventing accidental changes.
BIt automatically persists state to local storage without extra code.
CIt delays emissions until all subscribers are ready, ensuring synchronized updates.
DIt holds the current state and immediately emits the latest value to new subscribers, enabling reactive UI updates.
Attempts:
2 left
💡 Hint

Think about how BehaviorSubject differs from a regular Subject.

Practice

(1/5)
1. What is the main purpose of using BehaviorSubject in Angular as a simple store?
easy
A. To hold and share the latest value with all subscribers immediately
B. To perform HTTP requests automatically
C. To create Angular components dynamically
D. To manage routing between pages

Solution

  1. Step 1: Understand BehaviorSubject role

    BehaviorSubject holds a current value and shares it with subscribers immediately when they subscribe.
  2. Step 2: Compare with other options

    The other options describe unrelated Angular features like HTTP, components, and routing.
  3. Final Answer:

    To hold and share the latest value with all subscribers immediately -> Option A
  4. Quick Check:

    BehaviorSubject shares latest value immediately [OK]
Hint: BehaviorSubject always gives current value to new subscribers [OK]
Common Mistakes:
  • Confusing BehaviorSubject with HTTP or routing
  • Thinking it delays value delivery
  • Assuming it creates components
2. Which of the following is the correct way to update the value stored in a BehaviorSubject named store$?
easy
A. store$.update(newValue);
B. store$.next(newValue);
C. store$.setValue(newValue);
D. store$.emit(newValue);

Solution

  1. Step 1: Recall BehaviorSubject update method

    The method to update a BehaviorSubject's value is next().
  2. Step 2: Check other method names

    Methods like update(), setValue(), and emit() do not exist on BehaviorSubject.
  3. Final Answer:

    store$.next(newValue); -> Option B
  4. Quick Check:

    Use next() to update BehaviorSubject [OK]
Hint: Use next() to push new values to BehaviorSubject [OK]
Common Mistakes:
  • Using update() or setValue() instead of next()
  • Confusing EventEmitter with BehaviorSubject
  • Trying to assign value directly
3. Given this Angular code snippet, what will be logged to the console?
const store$ = new BehaviorSubject(0);
store$.subscribe(value => console.log('Subscriber 1:', value));
store$.next(5);
store$.subscribe(value => console.log('Subscriber 2:', value));
store$.next(10);
medium
A. Subscriber 1: 0 Subscriber 2: 0 Subscriber 1: 5 Subscriber 2: 5 Subscriber 1: 10 Subscriber 2: 10
B. Subscriber 1: 0 Subscriber 1: 5 Subscriber 2: 0 Subscriber 1: 10 Subscriber 2: 10
C. Subscriber 1: 0 Subscriber 1: 5 Subscriber 2: 5 Subscriber 1: 10 Subscriber 2: 10
D. Subscriber 1: 5 Subscriber 2: 5 Subscriber 1: 10 Subscriber 2: 10

Solution

  1. Step 1: Trace first subscription

    Subscriber 1 subscribes first and immediately receives initial value 0, then receives 5 after next(5).
  2. Step 2: Trace second subscription

    Subscriber 2 subscribes after next(5), so it immediately receives current value 5.
  3. Step 3: Trace next(10) call

    Both subscribers receive 10 after next(10).
  4. Final Answer:

    Subscriber 1: 0 Subscriber 1: 5 Subscriber 2: 5 Subscriber 1: 10 Subscriber 2: 10 -> Option C
  5. Quick Check:

    BehaviorSubject sends current value on subscribe [OK]
Hint: New subscribers get latest value immediately [OK]
Common Mistakes:
  • Assuming second subscriber gets initial 0 instead of 5
  • Missing initial value emission on subscribe
  • Confusing order of console logs
4. Identify the error in this Angular code using BehaviorSubject as a simple store:
const store$ = new BehaviorSubject();
store$.subscribe(value => console.log(value));
store$.next(42);
medium
A. subscribe() must be called with an object, not a function
B. next() cannot be called after subscribe()
C. BehaviorSubject cannot emit numbers
D. BehaviorSubject requires an initial value when created

Solution

  1. Step 1: Check BehaviorSubject constructor

    BehaviorSubject requires an initial value passed to its constructor; here it is missing.
  2. Step 2: Validate other statements

    Calling next() after subscribe() is valid; subscribe() accepts a function; BehaviorSubject can emit numbers.
  3. Final Answer:

    BehaviorSubject requires an initial value when created -> Option D
  4. Quick Check:

    BehaviorSubject must have initial value [OK]
Hint: Always provide initial value to BehaviorSubject constructor [OK]
Common Mistakes:
  • Omitting initial value in constructor
  • Thinking next() can't be called after subscribe()
  • Confusing subscribe() argument types
5. You want to create a simple store using BehaviorSubject to hold a user's profile object and update it safely. Which approach correctly updates only the user's name without losing other profile data?
const profile$ = new BehaviorSubject({ name: 'Alice', age: 30 });
// Update name to 'Bob' here
hard
A. profile$.next({ ...profile$.value, name: 'Bob' });
B. profile$.next({ name: 'Bob' });
C. profile$.value.name = 'Bob';
D. profile$.update({ name: 'Bob' });

Solution

  1. Step 1: Understand BehaviorSubject value update

    Directly assigning to value property does not notify subscribers; next() must be called with full updated object.
  2. Step 2: Preserve existing data while updating name

    Use spread operator to copy existing profile and override name, then call next() with new object.
  3. Step 3: Check other options

    profile$.next({ name: 'Bob' }); loses age property; profile$.value.name = 'Bob'; mutates value without notification; profile$.update({ name: 'Bob' }); uses non-existent update() method.
  4. Final Answer:

    profile$.next({ ...profile$.value, name: 'Bob' }); -> Option A
  5. Quick Check:

    Use next() with spread to update partial data [OK]
Hint: Use spread operator with next() to update partial store data [OK]
Common Mistakes:
  • Overwriting entire object losing other properties
  • Mutating value directly without next()
  • Using non-existent update() method