Subscribe options

Classes used in the examples

// Dummy message class
class TestMessage
{
    public TestMessage(int value)
    {
        Value = value;
    }

    public int Value
    {
        get;
        private set;
    }
}

// Dummy subscriber class
class Subscriber : ISubscriber<TestMessage>
{
    public Subscriber(string name)
    {
        _name = name;
    }

    private string _name;

    void ISubscriber<TestMessage>.HandleMessage(IMessage<TestMessage> message)
    {
        Console.WriteLine(string.Format("{0} - Receive TestMessage1, value={1}", _name, message.Data.Value));
    }
}

Add one subscriber

var subscriber = new Subscriber();
// if the subscriber only implements one message type generic type args are not needed
PubSubLite.Subscribe(subscriber);
//... with type arg
PubSubLite.Bus.Subscribe<TestMessage>(subscriber);

Add multiple subscribers for a message type

IEnumerable<ISubscriber<TestMessage>> CreateSubscribers(int numberToCreate)
{
    var subscribers = new List<ISubscriber<TestMessage>>();
    for (int x = 0; x < numberToCreate; x++)
    {
        subscribers.Add(new Subscriber(string.Format("Subscriber {0}", x)));
    }
    return subscribers;
}

// Create 10 subscribers and add them to the bus
 var subscribers = CreateSubscribers(10);
 PubSubLite.Bus.SubscribeAll(() => subscribers);

Last edited Nov 4, 2010 at 7:19 PM by swmal, version 8

Comments

No comments yet.