Debian Codegraph @

stream.go

raw symbols SCIP
1 package observer
2
3 // Stream represents the list of values a property is updated to. For every
4 // property update, that value is appended to the list in the order they
5 // happen. The value is discarded once you advance the stream. Please note
6 // that Stream is not goroutine safe: you cannot use the same stream on
7 // multiple goroutines concurrently. If you want to use multiple streams for
8 // the same property, either use Property.Observe (goroutine-safe) or use
9 // Stream.Clone (before passing it to another goroutine).
10 type Stream interface {
11 // Value returns the current value for this stream.
12 Value() interface{}
13
14 // Changes returns the channel that is closed when a new value is available.
15 Changes() chan struct{}
16
17 // Next advances this stream to the next state.
18 // You should never call this unless Changes channel is closed.
19 Next() interface{}
20
21 // HasNext checks whether there is a new value available.
22 HasNext() bool
23
24 // WaitNext waits for Changes to be closed, advances the stream and returns
25 // the current value.
26 WaitNext() interface{}
27
28 // Clone creates a new independent stream from this one but sharing the same
29 // Property. Updates to the property will be reflected in both streams but
30 // they may have different values depending on when they advance the stream
31 // with Next.
32 Clone() Stream
33 }
34
35 type stream struct {
36 state *state
37 }
38
39 func (s *stream) Clone() Stream {
40 return &stream{state: s.state}
41 }
42
43 func (s *stream) Value() interface{} {
44 return s.state.value
45 }
46
47 func (s *stream) Changes() chan struct{} {
48 return s.state.done
49 }
50
51 func (s *stream) Next() interface{} {
52 s.state = s.state.next
53 return s.state.value
54 }
55
56 func (s *stream) HasNext() bool {
57 select {
58 case <-s.state.done:
59 return true
60 default:
61 return false
62 }
63 }
64
65 func (s *stream) WaitNext() interface{} {
66 <-s.state.done
67 s.state = s.state.next
68 return s.state.value
69 }