-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubjects.js
More file actions
82 lines (65 loc) · 2.34 KB
/
subjects.js
File metadata and controls
82 lines (65 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* SUBJECTS : BehaviorSubject, ReplaySubject, AsyncSubject
* A Subject is like an observable but can be multicast to many Observers.
* Subjects are like Event Emitters: they maintain a registry of many listeners
*/
import { BehaviorSubject, ReplaySubject, Subject, AsyncSubject } from "rxjs";
//Subjects :
var subject1 = new Subject();
//subscriber 1
subject1.subscribe((res) => {
console.log("subscriber 1 ", res);
});
//subscriber 2
subject1.subscribe((res) => {
console.log("subscriber 2 ", res);
});
//subscriber 3
subject1.subscribe((res) => {
console.log("subscriber 3 ", res);
});
subject1.next(Math.random());
/**
* BehaviorSubject : It has an initial value and will immediately emit the initial value to any subscriber
* useful when you want to provide the last known value to new subscribers, such as the current state of an application or
* the latest data fetched from an API
*/
var behaviorSubject = new BehaviorSubject(100); //default value
behaviorSubject.subscribe((res) => {
console.log("behaviorSubject subscriber1", res); //will get default or last updated value
});
behaviorSubject.next(200);
behaviorSubject.subscribe((res) => {
console.log("behaviorSubject subscriber2", res); //will get last updated value
});
/**
* ReplaySubject: subject that can buffer and replay a specific number of values
* useful when you want to provide a history of values to new subscribers or
* when you need to cache values for later use
*/
var replaySubject = new ReplaySubject(2); //buffer size as 2.
replaySubject.next(111);
replaySubject.next(222);
replaySubject.next(333);
replaySubject.subscribe((res) => {
console.log("replaySubject subscription1 ", res);
});
replaySubject.next(444);
replaySubject.subscribe((res) => {
console.log("replaySubject subscription2 ", res);
});
/**
* AsyncSubject: It will not emit any values until the subject’s complete() method is called.
* When completed, it will emit the last value (if any) to subscribers
*/
const asyncSubject = new AsyncSubject();
asyncSubject.subscribe((res) => {
console.log('asyncSubject Subscriber1 ', res);
});
asyncSubject.next(111);
asyncSubject.next(222);
asyncSubject.subscribe((res) => {
console.log('asyncSubject Subscriber2 ', res);
});
asyncSubject.next(333);
asyncSubject.complete();