2016-12-29 16:17:12 -05:00
|
|
|
package signal
|
|
|
|
|
2017-01-28 15:24:46 -05:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
2016-12-29 16:17:12 -05:00
|
|
|
func executeAndFulfill(f func() error, done chan<- error) {
|
|
|
|
err := f()
|
|
|
|
if err != nil {
|
|
|
|
done <- err
|
|
|
|
}
|
|
|
|
close(done)
|
|
|
|
}
|
|
|
|
|
2018-03-14 22:32:10 -04:00
|
|
|
// ExecuteAsync executes a function asynchronously and return its result.
|
2016-12-29 16:17:12 -05:00
|
|
|
func ExecuteAsync(f func() error) <-chan error {
|
|
|
|
done := make(chan error, 1)
|
|
|
|
go executeAndFulfill(f, done)
|
|
|
|
return done
|
|
|
|
}
|
|
|
|
|
2017-01-28 15:24:46 -05:00
|
|
|
func ErrorOrFinish1(ctx context.Context, c <-chan error) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case err := <-c:
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ErrorOrFinish2(ctx context.Context, c1, c2 <-chan error) error {
|
2016-12-29 16:17:12 -05:00
|
|
|
select {
|
2017-01-28 15:24:46 -05:00
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
2017-04-17 13:33:22 -04:00
|
|
|
case err := <-c1:
|
|
|
|
if err != nil {
|
2016-12-29 16:17:12 -05:00
|
|
|
return err
|
|
|
|
}
|
2017-01-28 15:24:46 -05:00
|
|
|
return ErrorOrFinish1(ctx, c2)
|
2017-04-17 13:33:22 -04:00
|
|
|
case err := <-c2:
|
|
|
|
if err != nil {
|
2016-12-29 16:17:12 -05:00
|
|
|
return err
|
|
|
|
}
|
2017-01-28 15:24:46 -05:00
|
|
|
return ErrorOrFinish1(ctx, c1)
|
2016-12-29 16:17:12 -05:00
|
|
|
}
|
|
|
|
}
|