What is the difference between BehaviorSubject and a regular Subject

Jorge Vergara pointing at a target showing an arrow in the bullseye

Both BehaviorSubject and Subject are a type of Observable that we can use to stream data throughout our application.

The main difference, is that the BehaviorSubject has an initial value, and when you subscribe to it, it will give you the last value it emitted.

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  myBehaviosSubject$ = new BehaviorSubject<string>('I have an initial value');
  myRegularSubject$ = new Subject<string>();
  constructor() {}
}

The regular Subject doesn’t have an initial value, and even if it has been emitting data, when you subscribe to it you won’t get any data until it emits something again.

You can see the full app example directly in its GitHub repo here.