Created
January 17, 2013 13:19
-
-
Save luisrudge/4555889 to your computer and use it in GitHub Desktop.
does this makes sense?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using Microsoft.AspNet.SignalR.Client; | |
using Microsoft.AspNet.SignalR.Client.Hubs; | |
using TecUnica.Core; | |
namespace TecUnica.PubSub | |
{ | |
public class Subscriber : ISubscriber | |
{ | |
private readonly HubConnection _connection; | |
private readonly IHubProxy _hub; | |
public Subscriber() | |
{ | |
_connection = new HubConnection(ConfigurationHelper.GetConfiguration("TecUnica.PubSub.HubUrl", true)); | |
_hub = _connection.CreateHubProxy("PubSubHub"); | |
} | |
/// <summary> | |
/// Subscribe to a topic | |
/// </summary> | |
/// <typeparam name="T">type of object the action will receive</typeparam> | |
/// <param name="topic">topic</param> | |
/// <param name="handler">action to be executed</param> | |
public async void Subscribe<T>(string topic, Action<T> handler) | |
{ | |
_hub.On(topic, handler); | |
await _connection.Start(); | |
} | |
/// <summary> | |
/// When the connection stops | |
/// </summary> | |
/// <param name="handler">action to be executed</param> | |
public void OnDisconnect(Action handler) | |
{ | |
_connection.StateChanged += state => { if (state.NewState.Equals(ConnectionState.Disconnected)) handler.Invoke(); }; | |
} | |
/// <summary> | |
/// Unsubscribe from topic | |
/// </summary> | |
/// <param name="topic">topic</param> | |
public void Unsubscribe(string topic) | |
{ | |
if (!_connection.State.Equals(ConnectionState.Connected)) return; | |
_hub.On(topic, () => { }); | |
} | |
} | |
} |
_hub.On actually returns IDisposable
LOOL i wrote iObservable.. thanks David
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
_hub.On returns an IObservable... so you can store a ref to it and just call dispose when you want to unsubscribe