Search code examples
c#websocketmaui.net-maui

MAUI websocket without MVVM


I am trying to learn how to create mobile apps using MAUI and have seen many MVVM examples which I find incomplete. For this reason, I thought I should try to learn MAUI using CodeBehind first before moving onto MVVM. I have completey the MAUI section from the Microsoft Learn website, but it didn't cover displaying websocket data in XAML.

I have the following:

XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CodeBehindTicker.MainPage">

    <ScrollView>
        <VerticalStackLayout>

            <Label
                Text="Ticker value"
                x:Name="lblTicker" />

            <Button
                x:Name="btnGetTicker"
                Text="Get Ticker"
                Clicked="btnGetTicker_Clicked"/>

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

CodeBehind:

using Binance.Net.Clients;
using Binance.Net.Objects;

namespace CodeBehindTicker;

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

    private void btnGetTicker_Clicked(object sender, EventArgs e)
    {
        var socketClient = new BinanceSocketClient(new BinanceSocketClientOptions { });

        socketClient.SpotStreams.SubscribeToBookTickerUpdatesAsync("BTCUSDT", data => {

            lblTicker.Text = data.Data.BestAskPrice.ToString();
            Console.WriteLine(data.Data.BestAskPrice.ToString());

        });

        socketClient.UnsubscribeAllAsync();
    }
}

When I click the button, the websocket data displays in realtime in the console output, but the label only displays the very first data returned and does not automatically update as the data in the console output updates instantly.

Any idea why? For now, I just want to stick to basic CodeBehind without using MVVM.


Solution

  • My guess is since you are using A WebSocket which probably has some async code the text is not changed on the main thread.

    All you need to do is something like this:

    MainThread.BeginInvokeOnMainThread(() =>            
        lblTicker.Text = data.Data.BestAskPrice.ToString());