Skip to content

Commit

Permalink
update(Context): add Wait and WithNewWaitGroup methods
Browse files Browse the repository at this point in the history
  • Loading branch information
b97tsk committed Mar 10, 2024
1 parent 08ddad3 commit 19b7e51
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
13 changes: 13 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ func (c Context) Err() error {
return c.Context.Err()
}

// Wait runs c.WaitGroup.Wait().
// If c.WaitGroup is not set, Wait panics.
func (c Context) Wait() {
c.WaitGroup.Wait()
}

// AfterFunc arranges to call f in its own goroutine after c is done
// (cancelled or timed out).
// If c is already done, AfterFunc calls f immediately in its own goroutine.
Expand Down Expand Up @@ -139,6 +145,13 @@ func (c Context) WithTimeoutCause(timeout time.Duration, cause error) (Context,
return c.WithDeadlineCause(time.Now().Add(timeout), cause)
}

// WithNewWaitGroup returns a copy of c with WaitGroup field set to
// a new [sync.WaitGroup].
func (c Context) WithNewWaitGroup() Context {
c.WaitGroup = new(sync.WaitGroup)
return c
}

// WithWaitGroup returns a copy of c with WaitGroup field set to wg.
func (c Context) WithWaitGroup(wg *sync.WaitGroup) Context {
c.WaitGroup = wg
Expand Down
7 changes: 2 additions & 5 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rx_test
import (
"context"
"fmt"
"sync"
"time"

"github.com/b97tsk/rx"
Expand Down Expand Up @@ -84,9 +83,7 @@ func Example_blocking() {
}

func Example_waitGroup() {
var wg sync.WaitGroup

ctx := rx.NewContext(context.TODO()).WithWaitGroup(&wg)
ctx := rx.NewContext(context.TODO()).WithNewWaitGroup()

ctx.Go(func() {
for n := 1; n < 4; n++ {
Expand All @@ -98,7 +95,7 @@ func Example_waitGroup() {
}
})

wg.Wait()
ctx.Wait()

// Output:
// 1
Expand Down

0 comments on commit 19b7e51

Please sign in to comment.