Consuming value groups¶
To consume a value group of type T
,
you have to tag a []T
dependency with group:"$name"
where $name
is the name of the value group.
You can do this in one of the following ways:
- with parameter objects
- with annotated functions
With parameter objects¶
You can use parameter objects to tag a slice parameter of a function as a value group.
Prerequisites
-
A function that consumes a parameter object.
type Params struct { fx.In // ... } func New(p Params) (Result, error) { // ...
-
This function is provided to the Fx application.
fx.Provide(New),
Steps
-
Add a new exported field to the parameter object with the type
[]T
, whereT
is the kind of value in the value group. Tag this field with the name of the value group.type Params struct { fx.In // ... Watchers []Watcher `group:"watchers"` }
-
Consume this slice in the function that takes this parameter object.
func New(p Params) (Result, error) { // ... for _, w := range p.Watchers { // ...
Warning
Do not rely on the order of values inside the slice. The order is randomized.
With annotated functions¶
You can use annotations to consume a value group from an existing function.
Prerequisites
-
A function that accepts a slice of the kind of values in the group.
func NewEmitter(watchers []Watcher) (*Emitter, error) {
-
The function is provided to the Fx application.
fx.Provide( NewEmitter, ),
Steps
-
Wrap the function passed into
fx.Provide
withfx.Annotate
.fx.Provide( fx.Annotate( NewEmitter, ), ),
-
Annotate this function to state that its slice parameter is a value group.
fx.Annotate( NewEmitter, fx.ParamTags(`group:"watchers"`), ),
-
Consume this slice in the function.
func NewEmitter(watchers []Watcher) (*Emitter, error) { for _, w := range watchers { // ...
Functions can accept variadic arguments
You can consume a value group from a function that accepts variadic arguments instead of a slice.
func EmitterFrom(watchers ...Watcher) (*Emitter, error) {
Annotate the variadic argument like it was a slice to do this.
fx.Annotate(
EmitterFrom,
fx.ParamTags(`group:"watchers"`),
),