0Pricing
Angular Academy · Lesson

Subjects and BehaviorSubject

Multicast values with subjects.

What is a Subject

A Subject is both an Observable and an Observer. You can subscribe to it and also push values into it with next(). It multicasts: all subscribers receive the same emissions.

Creating and using a Subject

Subscribers added after a value is emitted will not receive past values.

import { Subject } from 'rxjs';

const events$ = new Subject<string>();
events$.subscribe(v => console.log('A:', v));

events$.next('hello'); // A: hello
events$.subscribe(v => console.log('B:', v));
events$.next('world'); // A: world, B: world

All lessons in this course

  1. Observables and Subscriptions
  2. Subjects and BehaviorSubject
  3. Unsubscribing and Memory Leaks
  4. The async Pipe
← Back to Angular Academy