-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatuslineblockprovider.go
54 lines (42 loc) · 1.2 KB
/
statuslineblockprovider.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
package dsts
import (
"context"
"sync/atomic"
)
// StatusLineBlockProvider is a simplified way of producing status line blocks.
//
// The function can run a loop and pass any updates to `ch`. It's meant to be
// called in its own goroutine, so it can block as long as needed, returning
// only when there's an error or when `ctx` is done.
type StatusLineBlockProvider func(ctx context.Context, ch chan<- StatusLineBlock) error
func slbpToNotifier(ctx context.Context, p StatusLineBlockProvider) (Notifier, *atomic.Pointer[StatusLineBlock]) {
statusLineBlock := &atomic.Pointer[StatusLineBlock]{}
notifier := UpdateNotifier(func(callback NotifierCallbackFunc) RemoveCallbackFunc {
ch := make(chan StatusLineBlock)
ctxProvider, cancel := context.WithCancelCause(ctx)
go func(ctxProvider context.Context, ch chan<- StatusLineBlock) {
err := p(ctxProvider, ch)
if err != nil {
cancel(err)
return
}
cancel(nil)
}(ctxProvider, ch)
go func() {
for {
select {
case <-ctx.Done():
return
case status := <-ch:
statusLineBlock.Store(&status)
callback()
}
}
}()
remove := func() {
cancel(nil)
}
return remove
})
return notifier, statusLineBlock
}