-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautoconnect.go
42 lines (39 loc) · 1004 Bytes
/
autoconnect.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
package rx
import (
"sync"
"sync/atomic"
)
const InvalidCount = Error("invalid count")
func (connectable Connectable[T]) AutoConnect(count int) Observable[T] {
if count < 1 {
return Throw[T](InvalidCount)
}
var source struct {
sync.Mutex
refcount int32
subscription *subscription
}
observable := func(observe Observer[T], scheduler Scheduler, subscriber Subscriber) {
subscriber.OnUnsubscribe(func() {
source.Lock()
if atomic.AddInt32(&source.refcount, -1) == 0 {
if source.subscription != nil {
source.subscription.Unsubscribe()
}
}
source.Unlock()
})
connectable.Observable(observe, scheduler, subscriber)
source.Lock()
if atomic.AddInt32(&source.refcount, 1) == int32(count) {
if source.subscription == nil || source.subscription.err != nil {
source.subscription = newSubscription(scheduler)
source.Unlock()
connectable.Connect(scheduler, source.subscription)
source.Lock()
}
}
source.Unlock()
}
return observable
}