🌐 Networking & APIs
Real-Time with SignalR
HubConnection, On(), automatic reconnect, live data.

SignalR Client Setup

bash
dotnet add package Microsoft.AspNetCore.SignalR.Client
csharp
public class ChatService
{
    HubConnection? _hub;

    public async Task ConnectAsync(string token)
    {
        _hub = new HubConnectionBuilder()
            .WithUrl("https://api.example.com/chathub", opts =>
                opts.AccessTokenProvider = () => Task.FromResult(token)!)
            .WithAutomaticReconnect()
            .Build();

        // Subscribe to server-pushed messages
        _hub.On<string, string>("ReceiveMessage", (user, msg) =>
            MainThread.BeginInvokeOnMainThread(() =>
                Messages.Add(new ChatMessage(user, msg))));

        await _hub.StartAsync();
    }

    public async Task SendAsync(string msg) =>
        await _hub!.SendAsync("SendMessage", msg);

    public async Task DisconnectAsync() =>
        await _hub!.StopAsync();
}
💡
WithAutomaticReconnect() handles network drops with exponential backoff — no manual reconnection logic needed.

Key Takeaways

Microsoft.AspNetCore.SignalR.Client works on Android via MAUI
Hub.On() subscribes to server-pushed events
Always update UI on the main thread with MainThread.BeginInvokeOnMainThread
WithAutomaticReconnect() retries after network drops automatically
Lesson 24 of 30Networking & APIs
← Previous Next Lesson →