Feeding value groups¶
To feed values to a value group of type T
,
you have to tag a T
result with group:"$name"
where $name
is the name of the value group.
You can do this in one of the following ways:
- with result objects
- with annotated functions
With result objects¶
You can use result objects to tag the result of a function and feed it into a value group.
Prerequisites
-
A function that produces a result object.
type Result struct { fx.Out // ... } func New( /* ... */ ) (Result, error) { // ... return Result{ // ... Watcher: watcher, }, nil }
-
The function is provided to the Fx application.
fx.Provide(New),
Steps
-
Add a new exported field to the result object with the type of value you want to produce, and tag the field with the name of the value group.
type Result struct { fx.Out // ... Watcher Watcher `group:"watchers"` }
-
In the function, set this new field to the value that you want to feed into the value group.
func New( /* ... */ ) (Result, error) { // ... watcher := &watcher{ // ... } return Result{ // ... Watcher: watcher, }, nil }
With annotated functions¶
You can use annotations to send the result of an existing function to a value group.
Prerequisites
-
A function that produces a value of the type required by the group.
func NewWatcher( /* ... */ ) (Watcher, error) { // ...
-
The function is provided to the Fx application.
fx.Provide( NewWatcher, ),
Steps
-
Wrap the function passed into
fx.Provide
withfx.Annotate
.fx.Provide( fx.Annotate( NewWatcher, ), ),
-
Annotate this function to state that its result feeds into the value group.
fx.Annotate( NewWatcher, fx.ResultTags(`group:"watchers"`), ),
Types don't always have to match
If the function you're annotating does not produce the same type as the group, but it can be cast into that type:
func NewFileWatcher( /* ... */ ) (*FileWatcher, error) {
You can still use annotations to provide it to a value group.
fx.Annotate(
NewFileWatcher,
fx.As(new(Watcher)),
fx.ResultTags(`group:"watchers"`),
),
See casting structs to interfaces for more details.