Skip to content

Commit

Permalink
feat: add Subscribe for easy using
Browse files Browse the repository at this point in the history
  • Loading branch information
jizhuozhi committed Aug 1, 2024
1 parent 6529b0f commit 4b35def
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions future.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@ func (f *Future[T]) GetOrDefault(defaultVal T) T {
return val
}

func (f *Future[T]) Subscribe(cb func(val T, err error)) {
f.state.subscribe(cb)
}

// noCopy may be embedded into structs which must not be copied
// after the first use.
//
Expand Down
16 changes: 16 additions & 0 deletions future_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ func TestPromiseSetTwice(t *testing.T) {
})
}

func TestFutureSubscribe(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
val1 := 0
val2 := 0
f.Subscribe(func(val int, err error) {
val1 = val + 1
})
f.Subscribe(func(val int, err error) {
val2 = val + 2
})
p.Set(1, nil)
assert.Equal(t, val1, 2)
assert.Equal(t, val2, 3)
}

func Benchmark(b *testing.B) {
b.Run("Promise", func(b *testing.B) {
for i := 0; i < b.N; i++ {
Expand Down

0 comments on commit 4b35def

Please sign in to comment.