-
Notifications
You must be signed in to change notification settings - Fork 1
/
groupby.go
44 lines (42 loc) · 908 Bytes
/
groupby.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
package rxgo
import (
"fmt"
"sync"
)
func GroupBy(fn func(v Value) Value, apply ...OperatorFunc) OperatorFunc {
return func(o Observable) Observable {
return Create(func(v ValueChan, e ErrChan, c CompleteChan) TeardownFunc {
var wg sync.WaitGroup
groups := make(map[string]Subject)
return o.Subscribe(
OnNext(
func(val Value) {
key := fmt.Sprint(fn(val))
if group, ok := groups[key]; ok {
group.Next(val)
} else {
wg.Add(1)
groups[key] = NewSubject()
groups[key].
Pipe(apply...).
Subscribe(
OnNext(v.Next).
OnErr(e.Error).
OnComplete(wg.Done),
)
groups[key].Next(val)
}
},
).
OnErr(e.Error).
OnComplete(func() {
for _, group := range groups {
group.Complete()
}
wg.Wait()
c.Complete()
}),
).Unsubscribe
})
}
}