Learn about Behavioral Subjects in RxJS | Practical Code Example

BehaviorSubjects are a type of Observable in RxJS library that are useful when you need to share data between components or services. They allow you to publish a stream of values to multiple subscribers, who will receive the current value of the stream upon subscription and all subsequent updates to the stream.

Here's a practical code example that illustrates how to use BehaviorSubject in RxJS:

typescript
import { BehaviorSubject } from 'rxjs';

// Create a new BehaviorSubject with an initial value
const subject = new BehaviorSubject('Hello');

// Subscribe to the BehaviorSubject
subject.subscribe(value => console.log(`Subscriber 1: ${value}`));

// Output: Subscriber 1: Hello

// Update the BehaviorSubject's value
subject.next('World');

// Output: Subscriber 1: World

// Subscribe to the BehaviorSubject again
subject.subscribe(value => console.log(`Subscriber 2: ${value}`));

// Output: Subscriber 2: World

// Update the BehaviorSubject's value again
subject.next('Hello again');

// Output: Subscriber 1: Hello again
//         Subscriber 2: Hello again

In this example, we create a new BehaviorSubject and subscribe to it twice. When we update the value of the BehaviorSubject using `subject.next('World')`, both subscribers receive the updated value. When we subscribe to the BehaviorSubject again, the second subscriber receives the current value of the stream ('World') and all subsequent updates. Finally, when we update the value of the BehaviorSubject again using `subject.next('Hello again')`, both subscribers receive the updated value.