Skip to content

Instantly share code, notes, and snippets.

@philiplaureano
Created July 1, 2017 11:09
Show Gist options
  • Save philiplaureano/b2a1f9e1164d6128f01751e96be1c4b6 to your computer and use it in GitHub Desktop.
Save philiplaureano/b2a1f9e1164d6128f01751e96be1c4b6 to your computer and use it in GitHub Desktop.
A base class for Proto.Actor that makes it easier to migrate actors between Akka.NET and Proto.Actor
public abstract class ReceiveActor : IActor
{
private List<(Func<object, bool>, Action<object>)> _handlers = new List<(Func<object, bool>, Action<object>)>();
public async Task ReceiveAsync(IContext context)
{
if (context.Message is Restarting)
PreRestart(null, context.Message);
if (context.Message is Started)
PreStart();
if (context.Message is Stopped)
PostStop();
var matchingHandlers = _handlers
.Where(h => h.Item1(context.Message))
.Select(h => h.Item2)
.ToArray();
if (!matchingHandlers.Any())
return;
var targetHandler = matchingHandlers.First();
targetHandler(context.Message);
}
protected virtual void PreStart()
{
}
protected virtual void PreRestart(Exception reason, object message)
{
}
protected virtual void PostStop()
{
}
protected void Receive<T>(Action<T> messageHandler)
{
Func<object, bool> predicate = message => message is T;
Action<object> handler = message =>
{
messageHandler((T)message);
};
_handlers.Add((predicate, handler));
}
protected void Become(Action behavior)
{
// Clear the existing set of behaviors
_handlers.Clear();
// Note: This method assumes that each
// behavior action contains the necessary Receive<T> handlers
behavior();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment