20

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

Nipuna
  • 6,846
  • 9
  • 64
  • 87

2 Answers2

36

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);
    });
}
davidfowl
  • 37,120
  • 7
  • 93
  • 103
1

I hate to necro, but this thread lead me down a bit of a dark alleyway. It is in fact possible to use Reactive Extensions (Rx) to handle the subscriptions and in many cases this is preferable as it allows composition.

A decent enough article explaining the basics. The formatting is sadly a bit botched in the code examples but you can get there. https://www.safaribooksonline.com/blog/2014/02/10/signalr-rx-framework/

user106394
  • 49
  • 4
  • 1
    Hi, and welcome to Stack Overflow! Posting a good answer on an old thread is fine here (check out [answer] if you haven't already), but you should [edit] to quote the relevant part of your link in your answer in case the link goes down. – user812786 Sep 07 '16 at 21:29
  • I would, but if you read the article in question quoting it would take up rather a lot of space ;) – user106394 Sep 27 '16 at 14:22
  • And if you read [answer] - "Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline." The blog post isn't too long to summarize - even just adding one of the comparisons would make this answer more substantial. Taking up space is fine here if it's used for quality information! – user812786 Sep 27 '16 at 14:38