What is the difference between Subject and BehaviorSubject in RxJS? TypeScript examples
Hello everyone! I started learning Angular and RxJS, and I got confused about Subject and BehaviorSubject. Both seem to be used for creating an Observable with the ability to emit values, but I don't understand the key difference.
\n\nHere is an example I wrote. When I use Subject, subscribers that subscribe after a value is emitted do not receive that value:
import { Subject } from 'rxjs';\n\nconst subject = new Subject<number>();\n\nsubject.next(1); // Emit value before subscription\n\nsubject.subscribe({\n next: (v) => console.log('Subject subscriber A:', v)\n});\n\nsubject.next(2); // Emit after subscription\n// Result: Subject subscriber A: 2\n// Value 1 is lost\n\nAnd when I use BehaviorSubje
No answers yet.
Log in to leave an answer