-
-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Lazy instantiation for services with side effects (#98)
- Loading branch information
Showing
53 changed files
with
875 additions
and
648 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package lazy | ||
|
||
import "sync" | ||
|
||
type Lazy[T any] interface { | ||
Get() (T, error) | ||
// IfInitialized calls the given function if the value has been initialized (useful for shutdown logic) | ||
IfInitialized(func(T) error) error | ||
} | ||
|
||
func New[T any](fn func() (T, error)) Lazy[T] { | ||
return &lazy[T]{fn: fn} | ||
} | ||
|
||
type lazy[T any] struct { | ||
fn func() (T, error) | ||
mtx sync.Mutex | ||
v T | ||
err error | ||
done bool | ||
} | ||
|
||
func (l *lazy[T]) Get() (T, error) { | ||
l.mtx.Lock() | ||
defer l.mtx.Unlock() | ||
if !l.done { | ||
l.v, l.err = l.fn() | ||
l.done = true | ||
} | ||
return l.v, l.err | ||
} | ||
|
||
func (l *lazy[T]) IfInitialized(fn func(T) error) error { | ||
l.mtx.Lock() | ||
defer l.mtx.Unlock() | ||
if l.done { | ||
return fn(l.v) | ||
} | ||
return nil | ||
} |
Oops, something went wrong.