-
Notifications
You must be signed in to change notification settings - Fork 8
/
mono_just.go
98 lines (85 loc) · 1.71 KB
/
mono_just.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package mono
import (
"context"
"sync"
"sync/atomic"
"github.com/jjeffcaii/reactor-go"
"github.com/pkg/errors"
)
var _justSubscriptionPool = sync.Pool{
New: func() interface{} {
return new(justSubscription)
},
}
type monoJust struct {
value Any
}
type justSubscription struct {
actual reactor.Subscriber
parent *monoJust
n int32
}
func newMonoJust(v Any) *monoJust {
return &monoJust{
value: v,
}
}
func borrowJustSubscription() *justSubscription {
return _justSubscriptionPool.Get().(*justSubscription)
}
func returnJustSubscription(s *justSubscription) {
if s == nil {
return
}
s.actual = nil
s.parent = nil
atomic.StoreInt32(&s.n, 0)
_justSubscriptionPool.Put(s)
}
func (j *justSubscription) Request(n int) {
if j == nil || j.actual == nil || j.parent == nil {
return
}
if n < 1 {
returnJustSubscription(j)
panic(reactor.ErrNegativeRequest)
}
if !atomic.CompareAndSwapInt32(&j.n, 0, statComplete) {
return
}
defer returnJustSubscription(j)
if j.parent.value == nil {
j.actual.OnComplete()
return
}
defer func() {
rec := recover()
if rec == nil {
j.actual.OnComplete()
return
}
if e, ok := rec.(error); ok {
j.actual.OnError(errors.WithStack(e))
} else {
j.actual.OnError(errors.Errorf("%v", rec))
}
}()
j.actual.OnNext(j.parent.value)
}
func (j *justSubscription) Cancel() {
if j == nil || j.parent == nil || j.actual == nil {
return
}
atomic.CompareAndSwapInt32(&j.n, 0, statCancel)
}
func (m *monoJust) SubscribeWith(ctx context.Context, sub reactor.Subscriber) {
select {
case <-ctx.Done():
sub.OnError(reactor.NewContextError(ctx.Err()))
default:
su := borrowJustSubscription()
su.parent = m
su.actual = sub
sub.OnSubscribe(ctx, su)
}
}