Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR difference between On and Subscribe of IHubProxy

Tags:

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

like image 361
Nipuna Avatar asked Aug 06 '13 08:08

Nipuna


People also ask

What is Hub in SignalR?

What is a SignalR hub. The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server.

What is SignalR and how does it work?

SignalR is an abstraction over some of the transports that are required to do real-time work between client and server. SignalR first attempts to establish a WebSocket connection if possible. WebSocket is the optimal transport for SignalR because it has: The most efficient use of server memory.

Can SignalR be used in Web API?

Objective: Use SignalR for notification between Web API, and TypeScript/JavaScript based Web App, where Web API and the Web App is hosted in different domain. Enabling SignalR and CORS on Web API: Create a standard Web API project, and install the following NuGet packages: Microsoft.


2 Answers

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);
    });
}
like image 148
davidfowl Avatar answered Sep 18 '22 18:09

davidfowl


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/

like image 36
user106394 Avatar answered Sep 20 '22 18:09

user106394