-
Notifications
You must be signed in to change notification settings - Fork 0
/
behaviorSubject.go
50 lines (44 loc) · 1.41 KB
/
behaviorSubject.go
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
package rx
// BehaviorSubject is a variant of the simple subject struct that requires an
// initial value and emits its current value whenever it is subscribed to.
type BehaviorSubject struct {
observers []BehaviorObservable
currentValue interface{}
isStopped bool
}
// NewBehaviorSubject creates a new behavior subject structure.
func NewBehaviorSubject(initialValue interface{}) BehaviorSubject {
return BehaviorSubject{
currentValue: initialValue,
}
}
// Next notifies all subscribed observers with the given value.
func (s *BehaviorSubject) Next(value interface{}) {
if !s.isStopped {
s.currentValue = value
for _, observer := range s.observers {
observer.SetCurrentValue(s.currentValue)
observer.input() <- s.currentValue
}
}
}
// Error notifies all subscribed observers with the given error.
func (s *BehaviorSubject) Error(err error) {
s.isStopped = true
for _, observer := range s.observers {
observer.input() <- err
}
}
// Complete terminates this subject and notifies all subscribed observers.
func (s *BehaviorSubject) Complete() {
s.isStopped = true
for _, observer := range s.observers {
close(observer.input())
}
}
// Observable returns a new observable with this subject as source.
func (s *BehaviorSubject) Observable() Observable {
observable := NewBehaviorObservable(nil, s.currentValue)
s.observers = append(s.observers, observable.(BehaviorObservable))
return observable
}