From 6fc9aa092e33a5c540288dad1b6a4a2b6e4df694 Mon Sep 17 00:00:00 2001 From: Brad Moylan Date: Sun, 4 Sep 2022 17:59:34 -0700 Subject: [PATCH] MapContext --- refreshable/refreshable.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/refreshable/refreshable.go b/refreshable/refreshable.go index eb5c3499..51fa3b12 100644 --- a/refreshable/refreshable.go +++ b/refreshable/refreshable.go @@ -4,6 +4,10 @@ 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 +67,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.