I'm trying to get a list of items to update whenever a message is received from a message queue.
This only seems to work every other time a message is received though. It's definitely hitting the anonymous method inside the SubscribeAsync
call each time, and I can't work out why it's not updating every time. I'm assuming it's related to that anonymous method being in a different thread. Any ideas what I'm doing wrong?
@page "/"
@inject IMessageQueueHelperFactory MessageQueueHelperFactory
@inject ILogger<Index> Logger
@using Microsoft.Extensions.Logging
@using Newtonsoft.Json
<ul class="list-group">
@foreach (var user in Users) {
<li class="list-group-item">@user</li>
}
</ul>
@code
{
private List<string> Users { get; set; } = new List<string>();
protected override void OnInitialized()
{
MessageQueueHelperFactory.Create(Queues.UserRegistration)
.SubscribeAsync(async x =>
{
var user = JsonConvert.DeserializeObject<UserRegistrationData>(x);
Users.Add(user.Username);
await InvokeAsync(StateHasChanged);
});
base.OnInitialized();
}
}
From Microsoft's documentation, I came across this article: Component initialization methods
It says that:
Blazor Server apps that prerender their content call OnInitializedAsync twice
Once when the component is initially rendered statically as part of the page.
A second time when the browser establishes a connection back to the server.
So, I guess if you use OnAfterRenderAsync with the first parameter set to true will solve your problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With