Skip to content

Commit

Permalink
feat: change result of AllOf from struct{} to []T
Browse files Browse the repository at this point in the history
Signed-off-by: jizhuozhi <jizhuozhi.george@gmail.com>
  • Loading branch information
jizhuozhi committed Oct 23, 2024
1 parent b9b5395 commit 09a81f8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
17 changes: 10 additions & 7 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,28 +108,31 @@ func ToAny[T any](f *Future[T]) *Future[any] {
})
}

func AllOf[T any](fs ...*Future[T]) *Future[struct{}] {
func AllOf[T any](fs ...*Future[T]) *Future[[]T] {
if len(fs) == 0 {
return Done(struct{}{})
return Done[[]T](nil)
}

var done uint32
s := &state[struct{}]{}
s := &state[[]T]{}
c := int32(len(fs))
for _, f := range fs {
results := make([]T, len(fs))
for i, f := range fs {
i := i
f.state.subscribe(func(val T, err error) {
if err != nil {
if atomic.CompareAndSwapUint32(&done, 0, 1) {
s.set(struct{}{}, err)
s.set(nil, err)
}
} else {
results[i] = val
if atomic.AddInt32(&c, -1) == 0 {
s.set(struct{}{}, nil)
s.set(results, nil)
}
}
})
}
return &Future[struct{}]{state: s}
return &Future[[]T]{state: s}
}

func Timeout[T any](f *Future[T], d time.Duration) *Future[T] {
Expand Down
6 changes: 3 additions & 3 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,9 +327,9 @@ func TestAllOf(t *testing.T) {
}

f := AllOf(fs...)
_, err := f.Get()
results, err := f.Get()
assert.Equal(t, vals, results)
assert.NoError(t, err)

for i := 0; i < 10; i++ {
ff := fs[i]
val, err := ff.Get()
Expand All @@ -342,7 +342,7 @@ func TestAllOfEmpty(t *testing.T) {
fs := make([]*Future[int], 0)
f := AllOf(fs...)
r, err := f.Get()
assert.Equal(t, struct{}{}, r)
assert.Equal(t, []int(nil), r)
assert.NoError(t, err)
}

Expand Down

0 comments on commit 09a81f8

Please sign in to comment.