Skip to content

Instantly share code, notes, and snippets.

@jermdavis
Last active April 18, 2021 08:04
Show Gist options
  • Save jermdavis/a28a0a60c913689a167754893c68afcc to your computer and use it in GitHub Desktop.
Save jermdavis/a28a0a60c913689a167754893c68afcc to your computer and use it in GitHub Desktop.
using System;
namespace StronglyTypedPipelines
{
public abstract class BasePipelineStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
public event Action<INPUT> OnInput;
public event Action<OUTPUT> OnOutput;
// note need for descendant types to implement this, not Process()
protected abstract OUTPUT ProcessStep(INPUT input);
public OUTPUT Process(INPUT input)
{
OnInput?.Invoke(input);
var output = ProcessStep(input);
OnOutput?.Invoke(output);
return output;
}
}
}
using System;
namespace StronglyTypedPipelines
{
public static class PipelineStepEventExtensions
{
public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPipelineStep<INPUT, OUTPUT> step, Action<INPUT> inputEvent = null, Action<OUTPUT> outputEvent = null)
{
if(inputEvent != null || outputEvent != null)
{
var eventDecorator = new EventStep<INPUT, OUTPUT>(step);
eventDecorator.OnInput += inputEvent;
eventDecorator.OnOutput += outputEvent;
return eventDecorator.Process(input);
}
return step.Process(input);
}
}
}
using System;
namespace StronglyTypedPipelines
{
public class EventStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
public event Action<INPUT> OnInput;
public event Action<OUTPUT> OnOutput;
private IPipelineStep<INPUT, OUTPUT> _innerStep;
public EventStep(IPipelineStep<INPUT,OUTPUT> innerStep)
{
_innerStep = innerStep;
}
public OUTPUT Process(INPUT input)
{
OnInput?.Invoke(input);
var output = _innerStep.Process(input);
OnOutput?.Invoke(output);
return output;
}
}
}
private static void EventPipelineTest()
{
Console.WriteLine("Event Pipeline Test");
var input = 49;
Console.WriteLine(string.Format("Input Value: {0} [{1}]", input, input.GetType().Name));
var pipeline = new EventStep<int, int>(new DoubleStep());
pipeline.OnInput += i => Console.WriteLine("Input event: " + i.ToString());
pipeline.OnOutput += o => Console.WriteLine("Output event: " + o.ToString());
var output = pipeline.Process(input);
Console.WriteLine(string.Format("Output Value: {0} [{1}]", output, output.GetType().Name));
Console.WriteLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment