Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update list of items in Blazor from another thread

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();
    }
}
like image 738
Dan Avatar asked Mar 08 '20 19:03

Dan


Video Answer


1 Answers

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

like image 87
vasilisdmr Avatar answered Oct 19 '22 11:10

vasilisdmr