-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.go
More file actions
50 lines (44 loc) · 1.32 KB
/
state.go
File metadata and controls
50 lines (44 loc) · 1.32 KB
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
package async
// A State is a [Signal] that carries a value.
// To retrieve the value, call the Get method.
//
// Calling the Set method of a state, in a [Task] function, updates the value
// and resumes any coroutine that is watching the state.
//
// A State must not be shared by more than one [Executor].
type State[T any] struct {
Signal
value T
}
// NewState creates a new [State] with its initial value set to v.
func NewState[T any](v T) *State[T] {
return &State[T]{value: v}
}
// Get retrieves the value of s.
//
// Without proper synchronization, one should only call this method in
// a [Task] function.
func (s *State[T]) Get() T {
return s.value
}
// Set updates the value of s and resumes any coroutine that is watching s.
//
// One should only call this method in a [Task] function.
func (s *State[T]) Set(v T) {
s.value = v
s.Notify()
}
// Update sets the value of s to f(s.Get()) and resumes any coroutine that
// is watching s.
//
// One should only call this method in a [Task] function.
func (s *State[T]) Update(f func(v T) T) {
s.Set(f(s.value))
}
// Await returns a [Task] that awaits until the value of s meets a specified
// condition, and then ends.
func (s *State[T]) Await(f func(v T) bool) Task {
return func(co *Coroutine) Result {
return co.Await(s).Until(func() bool { return f(s.value) }).End()
}
}