Skip to content

Commit

Permalink
MapContext
Browse files Browse the repository at this point in the history
  • Loading branch information
bmoylan committed Sep 5, 2022
1 parent 615f9a9 commit 89c7597
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions refreshable/refreshable.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit 89c7597

Please sign in to comment.