I have a little problem, I try to display live data on a page on my Blazor Server Project. After reading several stuff I think this should be possible to make with using INotifyPropertyChanged. Unfortunately I am a noob on this, here's what I tried:
My Model Price with INotifyPropertyChanged (generated using Rider):
public class Price : INotifyPropertyChanged
{
private double _askPrice;
private double _bidPrice;
private double _spread;
public Price(double askPrice, double bidPrice)
{
_askPrice = askPrice;
_bidPrice = bidPrice;
}
public double AskPrice {
get => _askPrice;
set
{
_askPrice = value;
OnPropertyChanged("AskPrice");
OnPropertyChanged("Spread");
}
}
public double BidPrice
{
get => _bidPrice;
set
{
_bidPrice = value;
OnPropertyChanged("BidPrice");
OnPropertyChanged("Spread");
}
}
public double Spread => _askPrice - _bidPrice;
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
How I get the live data:
public class PriceService
{
public static Price BinancePrice;
public static void StartBinanceStream()
{
var client = new BinanceSocketClient();
// subscribe to updates on the spot API
client.Spot.SubscribeToBookTickerUpdates("BTCEUR", data =>
{
BinancePrice = new Price((double)data.BestAskPrice, (double)data.BestBidPrice);
});
}
}
And finally the content of my razorfile:
<h5>BID: @($"{PriceService.BinancePrice.BidPrice:F2} EUR")</h5>
<h5>ASK: @($"{PriceService.BinancePrice.AskPrice:F2} EUR")</h5>
<h5>Spread: @($"{PriceService.BinancePrice.Spread:F2} EUR")</h5>
@code {
protected override async Task OnInitializedAsync()
{
PriceService.BinancePrice.PropertyChanged += async (sender, e) => { await InvokeAsync(StateHasChanged); };
await base.OnInitializedAsync();
}
async void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
await InvokeAsync(StateHasChanged);
}
public void Dispose()
{
PriceService.BinancePrice.PropertyChanged -= OnPropertyChangedHandler;
}
}
It does show the data but doesn't show it live with changes, I need to reopen the tab or refresh the page to see the current data. The goal is that the UI refreshes every time the Price is changing. Would be awesome if you could help me out on this!:)