Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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());

Hope this helps

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading