-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuture.go
More file actions
42 lines (37 loc) · 1023 Bytes
/
future.go
File metadata and controls
42 lines (37 loc) · 1023 Bytes
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
package devflow
// Future holds the async result of any initialization.
// It uses any (interface{}) for flexibility without generic syntax.
type Future struct {
result any
err error
done chan bool
}
// NewFuture starts async initialization with the given function.
func NewFuture(initFn func() (any, error)) *Future {
f := &Future{done: make(chan bool, 1)}
go func() {
f.result, f.err = initFn()
f.done <- true
close(f.done)
}()
return f
}
// NewResolvedFuture creates a Future that is already resolved with the given value.
// Useful for tests or when the value is already available synchronously.
func NewResolvedFuture(value any) *Future {
f := &Future{
result: value,
done: make(chan bool),
}
close(f.done) // Already done
return f
}
// Get blocks until initialization completes and returns the result.
func (f *Future) Get() (any, error) {
<-f.done
return f.result, f.err
}
// Ready returns a channel that signals completion.
func (f *Future) Ready() <-chan bool {
return f.done
}