Nipuna Nipuna - 2 months ago 33
C# Question

SignalR difference between On and Subscribe of IHubProxy

What are the differences between

On
and
Subscribe
methods available in
IHubProxy
interface. When should one use one over the other

Answer

Subscribe is lower level and you should really never have to use it. On provides friendlier overloads that allow for strong typing of arguments. Here's an example:

Server

public class MyHub
{
    public void Send(string message, int age)
    {
        Clients.All.send(message, age);
    }
}

Client

Subscribe pattern

public void Main()
{
    var connection = new HubConnection("http://myserver");
    var proxy = connection.CreateHubProxy("MyHub");

    var subscription = proxy.Subscribe("send");
    subscription.Received += arguments =>
    {
        string name = null;
        int age;
        if (arguments.Count > 0)
        {
            name = arguments[0].ToObject<string>();
        }

        if (arguments.Count > 1)
        {
            age = arguments[1].ToObject<int>();
        }

        Console.WriteLine("Name {0} and age {1}", name, age);
    };
}

"On" Pattern

public void Main()
{
    var connection = new HubConnection("http://myserver");
    var proxy = connection.CreateHubProxy("MyHub");

    proxy.On<string, int>("send", (name, age) =>
    {
        Console.WriteLine("Name {0} and age {1}", name, age);
    });
}
Comments