# StateMachineFragment

Base class for reusable state machine fragments.

Extends: [Construct](/cdk/api/v2/docs/constructs.Construct.html) › StateMachineFragment
Implements: [IChainable](/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions.IChainable.html), [IConstruct](/cdk/api/v2/docs/constructs.IConstruct.html), [IDependable](/cdk/api/v2/docs/constructs.IDependable.html)

- Source: [`aws-stepfunctions/lib/state-machine-fragment.ts`](https://github.com/aws/aws-cdk/blob/v2.277.0/packages/aws-cdk-lib/aws-stepfunctions/lib/state-machine-fragment.ts#L11)

## Example

TypeScript:

```ts
import { Stack } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';

interface MyJobProps {
  jobFlavor: string;
}

class MyJob extends sfn.StateMachineFragment {
  public readonly startState: sfn.State;
  public readonly endStates: sfn.INextable[];

  constructor(parent: Construct, id: string, props: MyJobProps) {
    super(parent, id);

    const choice = new sfn.Choice(this, 'Choice')
      .when(sfn.Condition.stringEquals('$.branch', 'left'), new sfn.Pass(this, 'Left Branch'))
      .when(sfn.Condition.stringEquals('$.branch', 'right'), new sfn.Pass(this, 'Right Branch'));

    // ...

    this.startState = choice;
    this.endStates = choice.afterwards().endStates;
  }
}

class MyStack extends Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);
    // Do 3 different variants of MyJob in parallel
    const parallel = new sfn.Parallel(this, 'All jobs')
      .branch(new MyJob(this, 'Quick', { jobFlavor: 'quick' }).prefixStates())
      .branch(new MyJob(this, 'Medium', { jobFlavor: 'medium' }).prefixStates())
      .branch(new MyJob(this, 'Slow', { jobFlavor: 'slow' }).prefixStates());

    new sfn.StateMachine(this, 'MyStateMachine', {
      definitionBody: sfn.DefinitionBody.fromChainable(parallel),
    });
  }
}
```

Python:

```python
from aws_cdk import Stack
from constructs import Construct
import aws_cdk.aws_stepfunctions as sfn

class MyJob(sfn.StateMachineFragment):

    def __init__(self, parent, id, *, jobFlavor):
        super().__init__(parent, id)

        choice = sfn.Choice(self, "Choice").when(sfn.Condition.string_equals("$.branch", "left"), sfn.Pass(self, "Left Branch")).when(sfn.Condition.string_equals("$.branch", "right"), sfn.Pass(self, "Right Branch"))

        # ...

        self.start_state = choice
        self.end_states = choice.afterwards().end_states

class MyStack(Stack):
    def __init__(self, scope, id):
        super().__init__(scope, id)
        # Do 3 different variants of MyJob in parallel
        parallel = sfn.Parallel(self, "All jobs").branch(MyJob(self, "Quick", job_flavor="quick").prefix_states()).branch(MyJob(self, "Medium", job_flavor="medium").prefix_states()).branch(MyJob(self, "Slow", job_flavor="slow").prefix_states())

        sfn.StateMachine(self, "MyStateMachine",
            definition_body=sfn.DefinitionBody.from_chainable(parallel)
        )
```

Java:

```java
import software.amazon.awscdk.Stack;
import software.constructs.Construct;
import software.amazon.awscdk.services.stepfunctions.*;

public class MyJobProps {
    private String jobFlavor;
    public String getJobFlavor() {
        return this.jobFlavor;
    }
    public MyJobProps jobFlavor(String jobFlavor) {
        this.jobFlavor = jobFlavor;
        return this;
    }
}

public class MyJob extends StateMachineFragment {
    public final State startState;
    public final INextable[] endStates;

    public MyJob(Construct parent, String id, MyJobProps props) {
        super(parent, id);

        Choice choice = new Choice(this, "Choice").when(Condition.stringEquals("$.branch", "left"), new Pass(this, "Left Branch")).when(Condition.stringEquals("$.branch", "right"), new Pass(this, "Right Branch"));

        // ...

        this.startState = choice;
        this.endStates = choice.afterwards().getEndStates();
    }
}

public class MyStack extends Stack {
    public MyStack(Construct scope, String id) {
        super(scope, id);
        // Do 3 different variants of MyJob in parallel
        Parallel parallel = new Parallel(this, "All jobs").branch(new MyJob(this, "Quick", new MyJobProps().jobFlavor("quick")).prefixStates()).branch(new MyJob(this, "Medium", new MyJobProps().jobFlavor("medium")).prefixStates()).branch(new MyJob(this, "Slow", new MyJobProps().jobFlavor("slow")).prefixStates());

        StateMachine.Builder.create(this, "MyStateMachine")
                .definitionBody(DefinitionBody.fromChainable(parallel))
                .build();
    }
}
```

C# / .NET:

```csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK;
using Constructs;
using Amazon.CDK.AWS.StepFunctions;

class MyJobProps
{
    public string JobFlavor { get; set; }
}

class MyJob : StateMachineFragment
{
    public State StartState { get; }
    public INextable[] EndStates { get; }

    public MyJob(Construct parent, string id, MyJobProps props) : base(parent, id)
    {

        var choice = new Choice(this, "Choice").When(Condition.StringEquals("$.branch", "left"), new Pass(this, "Left Branch")).When(Condition.StringEquals("$.branch", "right"), new Pass(this, "Right Branch"));

        // ...

        StartState = choice;
        EndStates = choice.Afterwards().EndStates;
    }
}

class MyStack : Stack
{
    public MyStack(Construct scope, string id) : base(scope, id)
    {
        // Do 3 different variants of MyJob in parallel
        var parallel = new Parallel(this, "All jobs").Branch(new MyJob(this, "Quick", new MyJobProps { JobFlavor = "quick" }).PrefixStates()).Branch(new MyJob(this, "Medium", new MyJobProps { JobFlavor = "medium" }).PrefixStates()).Branch(new MyJob(this, "Slow", new MyJobProps { JobFlavor = "slow" }).PrefixStates());

        new StateMachine(this, "MyStateMachine", new StateMachineProps {
            DefinitionBody = DefinitionBody.FromChainable(parallel)
        });
    }
}
```

Golang:

```go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/constructs-go/constructs"
import "github.com/aws/aws-cdk-go/awscdk"

type myJobProps struct {
	jobFlavor *string
}

type myJob struct {
	StateMachineFragment
	startState State
	endStates []INextable
}

func newMyJob(parent Construct, id *string, props myJobProps) *myJob {
	this := &myJob{}
	sfn.NewStateMachineFragment_Override(this, parent, id)

	choice := sfn.NewChoice(this, jsii.String("Choice")).When(sfn.Condition_StringEquals(jsii.String("$.branch"), jsii.String("left")), sfn.NewPass(this, jsii.String("Left Branch"))).When(sfn.Condition_StringEquals(jsii.String("$.branch"), jsii.String("right")), sfn.NewPass(this, jsii.String("Right Branch")))

	// ...

	this.startState = choice
	this.endStates = choice.Afterwards().EndStates
	return this
}

type myStack struct {
	Stack
}

func newMyStack(scope Construct, id *string) *myStack {
	this := &myStack{}
	newStack_Override(this, scope, id)
	// Do 3 different variants of MyJob in parallel
	parallel := sfn.NewParallel(this, jsii.String("All jobs")).Branch(newMyJob(this, jsii.String("Quick"), &myJobProps{
		jobFlavor: jsii.String("quick"),
	}).PrefixStates()).Branch(newMyJob(this, jsii.String("Medium"), &myJobProps{
		jobFlavor: jsii.String("medium"),
	}).PrefixStates()).Branch(newMyJob(this, jsii.String("Slow"), &myJobProps{
		jobFlavor: jsii.String("slow"),
	}).PrefixStates())

	sfn.NewStateMachine(this, jsii.String("MyStateMachine"), &StateMachineProps{
		DefinitionBody: sfn.DefinitionBody_FromChainable(parallel),
	})
	return this
}
```

## Initializer

TypeScript:

```ts
new StateMachineFragment(scope: Construct, id: string)
```

Python:

```python
StateMachineFragment(scope: Construct, id: str)
```

Java:

```java
new StateMachineFragment(Construct scope, String id)
```

C# / .NET:

```csharp
new StateMachineFragment(Construct scope, string id)
```

Golang:

```go
NewStateMachineFragment(Scope Construct, Id *string)
```

## Properties

- `endStates`: [INextable](/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions.INextable.html)[] — The states to chain onto if this fragment is used.

- `id`: string — Descriptive identifier for this chainable.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) — The tree node.

- `startState`: [State](/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions.State.html) — The start state of this state machine fragment.

## Methods

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `next(next: IChainable): Chain` — Continue normal execution with the given state.

- `prefixStates(prefix?: string): StateMachineFragment // chainable` — Prefix the IDs of all states in this state machine fragment.

  Use this to avoid multiple copies of the state machine all having the
  same state IDs.

  **Parameters**

  - `prefix` — The prefix to add.

- `toSingleState(options?: SingleStateOptions): Parallel` — Wrap all states in this state machine fragment up into a single state.

  This can be used to add retry or error handling onto this state
  machine fragment.

  Be aware that this changes the result of the inner state machine
  to be an array with the result of the state machine in it. Adjust
  your paths accordingly. For example, change 'outputPath' to
  '$[0]'.

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.

  **Parameters**

  - `mixins` — The mixins to apply.

  **Returns:** This construct for chaining
