Skip to content

Commit

Permalink
onLoaded
Browse files Browse the repository at this point in the history
Signed-off-by: Paweł Gronowski <[email protected]>
  • Loading branch information
vvoland committed Dec 8, 2024
1 parent 0dac04c commit b5b06b6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
5 changes: 5 additions & 0 deletions livefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type LiveFile[StateT any] struct {

defaultFunc func() StateT
errHandler func(context.Context, error)
onLoaded func(context.Context, *StateT)
}

// The default error handler used for all LiveFile instances created without an
Expand Down Expand Up @@ -117,6 +118,10 @@ func (lf *LiveFile[T]) forceLoad(ctx context.Context, file *os.File) {
}
if err != nil {
lf.errHandler(ctx, fmt.Errorf("invalid JSON: %w", err))
} else {
if lf.onLoaded != nil {
lf.onLoaded(ctx, &lf.cached)
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,14 @@ func WithErrorHandler[T any](f func(context.Context, error)) Opt[T] {
s.errHandler = f
}
}

// WithLoadedCallback sets the function that will be called when the file is
// reloaded from the filesystem.
// The function will be called with the context and a pointer to the new data.
// Any access to the data MUST happen inside the callback and MUST NOT be
// stored outside of it.
func WithLoadedCallback[T any](f func(context.Context, *T)) Opt[T] {
return func(s *LiveFile[T]) {
s.onLoaded = f
}
}

0 comments on commit b5b06b6

Please sign in to comment.