desertbit / closer

A simple, thread-safe closer for go
MIT License
6 stars 0 forks source link

Add NewWithCtx #16

Closed skaldesh closed 3 months ago

skaldesh commented 1 year ago

I had the following use case today:

// Create creates a new zip writer and adds images of the given product and run.
// If the provided context is done before the operation is finished, the context's error
// is returned.
func Create(
    ctx context.Context,
    locale string,
    w io.Writer,
    ip ImageProvider,
    data Data,
) (err error) {
    // Create the closer for this report.
    cl := closer.New()
    defer func() {
        cErr := cl.Close()
        if err == nil {
            err = cErr
        }
    }()

    // Connect the closer to the given context.
    go func() {
        select {
        case <-cl.ClosingChan():
        case <-ctx.Done():
            cl.Close_()
        }
    }()

        ...

Instead of having to manually connect a given Context with a new closer, how about we add a new constructor closer.NewWithCtx(context.Context) that creates a closer and starts this goroutine internally?

r0l1 commented 1 year ago

Good idea. But what if the closer is created via a OneWay/TwoWayCloser call? Maybe we should also add a second helper:

cl.CloseOnContextDone
skaldesh commented 1 year ago

True, did not consider One/Twoway stuff...

yep, connecting an existing closer to a given context is the correct solution, I guess.