func WithFunc()

in ctxtool/func.go [34:58]


func WithFunc(parent canceller, fn func()) (context.Context, context.CancelFunc) {
	ctx := FromCanceller(parent)

	if ctx.Err() != nil {
		// context already cancelled, call fn
		go fn()
		return ctx, func() {}
	}

	chCancel := make(chan struct{})
	chDone := make(chan struct{})
	fnCtx := &funcContext{
		Context: ctx,
		ch:      chDone,
	}

	go fnCtx.wait(chCancel, chDone, fn)

	var closeOnce sync.Once
	return fnCtx, func() {
		closeOnce.Do(func() {
			close(chCancel)
		})
	}
}