Skip to content

Instantly share code, notes, and snippets.

@Stephanvs
Forked from LarsKemmann/PublisherActor.cs
Created August 5, 2016 21:12
Show Gist options
  • Save Stephanvs/f30e3d9f06f858b4f91cd67b09ebe7d9 to your computer and use it in GitHub Desktop.
Save Stephanvs/f30e3d9f06f858b4f91cd67b09ebe7d9 to your computer and use it in GitHub Desktop.
Service Fabric pub/sub using ActorEvents
public interface IPublisherEvents
{
void OnPublished(object value);
}
public interface IPublisher : IActor, IActorEventPublisher<IPublisherEvents>
{
Task PublishAsync(object value);
}
public class PublisherActor : IPublisher
{
public Task PublishAsync(object value)
{
// Previously, would have to register a reminder for every 'value' received and manage a subscriber list
// containing actor IDs and application/service names -- and then still use ActorEvents for pub/sub to non-actor clients.
GetEvent<IPublisherEvents>().OnPublished(value);
return Task.FromResult(0);
}
}
var publisher = ActorProxy.Create<IPublisher>(...);
publisher.Publish("Test"); // Received by publisher but no one has subscribed
var subscriber = ActorProxy.Create<ISubscriber>(...);
subscriber.InitSubscription(publisher.ActorId);
publisher.Publish(42); // Received by publisher and forwarded to subscriber
public interface ISubscriber : IActor
{
Task InitSubscription(ActorId publisherId);
}
public class SubscriberActor : ISubscriber, IPublisherEvents
{
public async Task InitSubscription(ActorId publisherId)
{
var proxy = ActorProxy.Create<IPublisher>(publisherId);
await proxy.SubscribeAsync<IPublisherEvents>(this);
}
public void OnPublished(object value) { /* ... */ }
protected override Task OnActivateAsync() { /* If deactivated, this is not called before 'OnPublished' is called */ }
protected override Task OnDeactivateAsync() { /* If 'OnPublished' is called, the countdown to calling this (GC) is not reset */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment