-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchable.go
54 lines (42 loc) · 1.1 KB
/
watchable.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
package bucket
// a basic structure from which to cancel or observe an asynchronous action
type Watchable struct {
Success chan error
Cancel chan error
Failed chan error
// The final observable which the user is likely to read from. Though it can only be fired once it is buffered
// so that is may be ignored.
Finished chan error
}
func NewWatchable() *Watchable {
watchable := &Watchable{ make(chan error), make(chan error), make(chan error), make(chan error, 2) }
watchable.listen()
return watchable
}
// Return the intended final observable
func (w *Watchable) Done() chan error {
return w.Finished
}
// Listen and response to various signals. It will only receive a maximum of one signal by design.
func (w *Watchable) listen() {
go func(){
select {
case err := <- w.Success:
w.Finished <- err
w.cleanup()
case err := <- w.Failed:
w.Finished <- err
w.cleanup()
}
}()
}
// Close all channels to prevent memory leaks.
func (w *Watchable) Close(err error){
w.Cancel <- err
}
func (w *Watchable) cleanup(){
close(w.Success)
close(w.Cancel)
close(w.Failed)
close(w.Finished)
}