Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions src/SignalR.EasyUse.Client/HubConnectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using SignalR.EasyUse.Interface;
Expand Down Expand Up @@ -38,9 +40,29 @@ public static T CreateNotInheritedHub<T>(this HubConnection hubConnection)
/// <typeparam name="T">Type of client method</typeparam>
/// <param name="connection">Connection to the hub that we subscribe to</param>
/// <param name="action">The action that will be executed when you call the customer</param>
public static void Subscribe<T>(this HubConnection connection, Action<T> action) where T : IClientMethod
public static IDisposable Subscribe<T>(this HubConnection connection, Action<T> action) where T : IClientMethod
{
SubscribeNotInherited<T>(connection, action);
return SubscribeNotInherited<T>(connection, action);
}

public static void Unsubscribe<T>(this HubConnection connection)
{
var recieveMessage = typeof(T);
var methodName = recieveMessage.Name;
connection.Remove(methodName);
}

public static void UnsubscribeAll(this HubConnection connection)
{
var type = connection.GetType();
var fieldInfo = type.GetField("_handlers", BindingFlags.NonPublic | BindingFlags.Instance);

dynamic handlers = fieldInfo.GetValue(connection);

if (!(handlers is IDictionary dict)) return;

var keys = dict.Keys;
foreach (string key in keys) connection.Remove(key);
}

/// <summary>
Expand All @@ -50,20 +72,22 @@ public static void Subscribe<T>(this HubConnection connection, Action<T> action)
/// <typeparam name="T">Type of client method</typeparam>
/// <param name="connection">Connection to the hub that we subscribe to</param>
/// <param name="action">The action that will be executed when you call the customer</param>
public static void SubscribeNotInherited<T>(this HubConnection connection, Action<T> action)
public static IDisposable SubscribeNotInherited<T>(this HubConnection connection, Action<T> action)
{
var recieveMessage = typeof(T);
var methodName = recieveMessage.Name;
var paramsList = recieveMessage.GetProperties()
.Select((info) => info.PropertyType)
.ToArray();

connection.On(methodName, paramsList,
objects =>
{
var instance = objects.CreateInstance<T>();
return Task.FromResult(action.DynamicInvoke(instance));
});
IDisposable subscription = connection.On(methodName, paramsList, (object[] args) =>
{
T instance = args.CreateInstance<T>();
action(instance);
return Task.CompletedTask;
});

return subscription;
}

/// <summary>
Expand Down
Loading