Xamarin SignalR - 在不同的片段/活动中使用相同的连接代理

时间:2016-06-11 13:57:46

标签: android xamarin signalr

是否可以将集线器连接传递给不同的片段和活动,以便在整个应用程序中使用相同的连接? 例如,代理连接的设置如下:

var chatHubProxy = hubConnection.CreateHubProxy("ChatHub");

我想在另一个片段中使用客户端方法chatHubProxy.On<string, int, string>("UpdateChatMessage", (message, color, user)。与调用服务器方法相同,我可以使用相同的代理在另一个片段/活动中调用它吗?

1 个答案:

答案 0 :(得分:1)

这很容易,让你的中心静止。或者甚至更好,处理Singleton中的所有SignalR内容,将逻辑集中在一个地方。

一种干净的方法是订阅该Singleton中的所有服务器事件,然后让该类重新调度您的自定义事件。这是一个工作应用程序的示例:

public event Action<string, User> OnShowMatchingInvite;
public event Action<MatchingResolutions, Conversation> OnMatchingResolution;
public event Action<string> OnPeerLeftConversation;
public event Action<ChatMessage> OnAddNewMessage;
public event Action<string, ChatMessageStatus> OnConfirmMessageDelivered;
public event Action<string> OnConfirmMessageReceived;
public event Action<string> OnConfirmMessageRead;
public event Action<UserChatStatus> OnChangeUserChatStatus;
public event Action<string> OnConversationKilled;

private void ProxySubscriber(IHubProxy hubProxy)
{
    hubProxy.On<string, User>(Settings.HubListenerShowMatchingInvite, 
            (matchingUid, peer) => OnShowMatchingInvite?.Invoke(matchingUid, peer));

    hubProxy.On<MatchingResolutions, Conversation>(Settings.HubListenerHandleMatchingResolution,
            (resolution, conversation) => OnMatchingResolution?.Invoke(resolution, conversation));

    hubProxy.On<string>(Settings.HubListenerPeerLeftConversation, 
            conversationId => OnPeerLeftConversation?.Invoke(conversationId));

    hubProxy.On<ChatMessage>(Settings.HubListenerAddNewMessage, 
            message => OnAddNewMessage?.Invoke(message));

    hubProxy.On<string, ChatMessageStatus>(Settings.HubListenerConfirmMessageDelivered, 
            (messageUid, status) => OnConfirmMessageDelivered?.Invoke(messageUid, status));

    hubProxy.On<string>(Settings.HubListenerConfirmMessageReceived, 
            uid => OnConfirmMessageReceived?.Invoke(uid));

    hubProxy.On<string>(Settings.HubListenerConfirmMessageRead, 
            uid => OnConfirmMessageRead?.Invoke(uid));

    hubProxy.On<UserChatStatus>(Settings.HubListenerChangeUserChatStatus, 
            status => OnChangeUserChatStatus?.Invoke(status));

    hubProxy.On<string>(Settings.HubListenerHandleConversationKilled,
            conversationId => OnConversationKilled?.Invoke(conversationId));
}

然后您可以订阅/取消订阅活动/片段中的那些事件:

protected override void OnPause()
{
    base.OnPause();
    // Don´t forget to unsubscribe
    YourSingleton.Instance.OnAddNewMessage -= OnAddNewMessage;
}

protected override void OnResume()
{
    base.OnResume();

    YourSingleton.Instance.OnAddNewMessage += OnAddNewMessage;
}

private void OnAddNewMessage(ChatMessage message)
{
    // TODO
}