Actor events
Actor events provide a way to send best-effort notifications from the actor to the clients. Actor events are designed for actor-to-client communication and shouldn't be used for actor-to-actor communication.
The following code snippets show how to use actor events in your application.
Define an interface that describes the events published by the actor. This interface must be derived from the IActorEvents
interface. The arguments of the methods must be data contract serializable. The methods must return void, as event notifications are one way and best effort.
public interface IGameEvents : IActorEvents
{
void GameScoreUpdated(Guid gameId, string currentScore);
}
public interface GameEvents implements ActorEvents
{
void gameScoreUpdated(UUID gameId, String currentScore);
}
Declare the events published by the actor in the actor interface.
public interface IGameActor : IActor, IActorEventPublisher<IGameEvents>
{
Task UpdateGameStatus(GameStatus status);
Task<string> GetGameScore();
}
public interface GameActor extends Actor, ActorEventPublisherE<GameEvents>
{
CompletableFuture<?> updateGameStatus(GameStatus status);
CompletableFuture<String> getGameScore();
}
On the client side, implement the event handler.
class GameEventsHandler : IGameEvents
{
public void GameScoreUpdated(Guid gameId, string currentScore)
{
Console.WriteLine(@"Updates: Game: {0}, Score: {1}", gameId, currentScore);
}
}
class GameEventsHandler implements GameEvents {
public void gameScoreUpdated(UUID gameId, String currentScore)
{
System.out.println("Updates: Game: "+gameId+" ,Score: "+currentScore);
}
}
On the client, create a proxy to the actor that publishes the event and subscribe to its events.
var proxy = ActorProxy.Create<IGameActor>(
new ActorId(Guid.Parse(arg)), ApplicationName);
await proxy.SubscribeAsync<IGameEvents>(new GameEventsHandler());
GameActor actorProxy = ActorProxyBase.create<GameActor>(GameActor.class, new ActorId(UUID.fromString(args)));
return ActorProxyEventUtility.subscribeAsync(actorProxy, new GameEventsHandler());
In the event of failovers, the actor may fail over to a different process or node. The actor proxy manages the active subscriptions and automatically re-subscribes them. You can control the re-subscription interval through the ActorProxyEventExtensions.SubscribeAsync<TEvent>
API. To unsubscribe, use the ActorProxyEventExtensions.UnsubscribeAsync<TEvent>
API.
On the actor, publish the events as they happen. If there are subscribers to the event, the Actors runtime sends them the notification.
var ev = GetEvent<IGameEvents>();
ev.GameScoreUpdated(Id.GetGuidId(), score);
GameEvents event = getEvent<GameEvents>(GameEvents.class);
event.gameScoreUpdated(Id.getUUIDId(), score);