chickensoft-games / LogicBlocks

Human-friendly, hierarchical and serializable state machines for games and apps in C#.
https://www.nuget.org/packages/Chickensoft.LogicBlocks
MIT License
181 stars 7 forks source link

How do you respond to output asynchronously? #38

Closed dodyg closed 3 months ago

dodyg commented 3 months ago

https://chickensoft.games/docs/logic_blocks/basics/outputs

using var binding = lightSwitch.Bind();

// Monitor an output:
binding.Handle((in LightSwitch.Output.StatusChanged output) =>
  System.Console.WriteLine(
    $"Status changed to {(output.IsOn ? "on" : "off")}"
  )
);

Is there any version of this that can call async code?

jolexxa commented 3 months ago

You can always call asynchronous code in C#, but you can't always await it. In this case, the binding closure cannot return a task because that would make output leave the stack, which would cause a memory allocation on every binding invocation.

There's nothing to stop you from doing this, though:

using var binding = lightSwitch.Bind();

// Monitor an output:
binding.Handle((in LightSwitch.Output.StatusChanged output) =>
  StartSomeAsynchronousTask().ContinueWith(result => ...);
);