-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmergeall.go
46 lines (44 loc) · 985 Bytes
/
mergeall.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
package rx
import (
"sync"
"sync/atomic"
)
func MergeAll[T any](observable Observable[Observable[T]]) Observable[T] {
return func(observe Observer[T], scheduler Scheduler, subscriber Subscriber) {
var merge struct {
sync.Mutex
done bool
count int32
}
merger := func(next T, err error, done bool) {
merge.Lock()
defer merge.Unlock()
if !merge.done {
switch {
case !done:
observe(next, nil, false)
case err != nil:
merge.done = true
var zero T
observe(zero, err, true)
default:
if atomic.AddInt32(&merge.count, -1) == 0 {
var zero T
observe(zero, nil, true)
}
}
}
}
appender := func(next Observable[T], err error, done bool) {
if !done {
atomic.AddInt32(&merge.count, 1)
next.AutoUnsubscribe()(merger, scheduler, subscriber)
} else {
var zero T
merger(zero, err, true)
}
}
merge.count += 1
observable.AutoUnsubscribe()(appender, scheduler, subscriber)
}
}