Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions workflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -512,3 +512,35 @@ func catchPanicAsError(f func() error) error {
}(&returnErr)
return returnErr
}

// SubWorkflow is a helper struct to let you create a step with a sub-workflow.
// Embed this struct to your struct definition.
//
// Usage:
//
// type MyStep struct {
// flow.SubWorkflow
// }
//
// func (s *MyStep) BuildStep() {
// s.Reset() // reset the workflow
// s.Add(
// flow.Step(/* stepX */),
// )
// }
//
// func main() {
// w := &flow.Workflow{}
// myStep := &MyStep{}
// w.Add(flow.Step(myStep)) // BuildStep() will be called when adding the step
// ...
// stepX := flow.As[*StepX](w) // we can get the inner stepX from the workflow
// }
type SubWorkflow struct{ w Workflow }

func (s *SubWorkflow) Unwrap() Steper { return &s.w }
func (s *SubWorkflow) Add(builders ...Builder) *Workflow { return s.w.Add(builders...) }
func (s *SubWorkflow) Do(ctx context.Context) error { return s.w.Do(ctx) }

// Reset resets the sub-workflow to ready for BuildStep()
func (s *SubWorkflow) Reset() { s.w = Workflow{} }
16 changes: 16 additions & 0 deletions workflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,3 +602,19 @@ func BenchmarkStatusChange(b *testing.B) {
w.Do(context.Background())
}
}

type StepSubWorkflow struct{ SubWorkflow }

func (s *StepSubWorkflow) BuildStep() {
s.Reset()
s.Add(Step(NoOp("inner")))
}

func TestSubWorkflow(t *testing.T) {
w := new(Workflow).Add(
Step(&StepSubWorkflow{}),
)
assert.NoError(t, w.Do(context.Background()))
assert.True(t, Has[*NoOpStep](w))
assert.Equal(t, "inner", As[*NoOpStep](w)[0].Name)
}