diff --git a/refreshable/refreshable.go b/refreshable/refreshable.go index eb5c3499f..f5ddcff98 100644 --- a/refreshable/refreshable.go +++ b/refreshable/refreshable.go @@ -4,6 +4,8 @@ package refreshable +import "context" + // A Refreshable is a generic container type for a volatile underlying value. // It supports atomic access and user-provided callback "subscriptions" on updates. type Refreshable[T any] interface { @@ -63,6 +65,16 @@ func Map[T any, M any](original Refreshable[T], mapFn func(T) M) (Refreshable[M] return out, stop } +// MapContext is like Map but unsubscribes when the context is cancelled. +func MapContext[T any, M any](ctx context.Context, original Refreshable[T], mapFn func(T) M) Refreshable[M] { + out, stop := Map(original, mapFn) + go func() { + <-ctx.Done() + stop() + }() + return out +} + // MapWithError is similar to Validate but allows for the function to return a mapping/mutation // of the input object in addition to returning an error. The returned validRefreshable will contain the mapped value. // An error is returned if the current original value fails to map.