Through a practical example to understand.
The following code creates a new subject and then calls the next method to multicast it to all its listeners.
import { Subject } from 'rxjs';
const jerry = new Subject();
const subscription = jerry.subscribe((data) => console.log(data));
console.log('ok');
jerry.next(111);
jerry.next(222);
subscription.unsubscribe();
console.log('?');
jerry.next(333);
The above example will print 111, 222
If the Subject starts multicasting before being subscribed (that is, 111 in line 5 of the figure below), then these multicast values will not be received by the subscribers after starting the multicast. As shown in the figure below: the subscriber will only print the multicast value 222 received after subscribing to the subject:
Using BehaviorSubject, you can avoid this problem: even before the subscriber subscribes to the subject, the latter starts to call next for multicast, these multicast values can also be received by the subscriber:
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。