Suppose I want a UI where users in a group have a synchronized view. Imagine a group-chat application, where everyone in the group should see the exact same messages.
Wh
I was trying to achieve something similar. After a while, I discovered a way of doing this. Kyle's answer helped me figure it out.
You must create a class, let's call Messenger, which has an Action property, and a method that invokes this Action once called
public Action OnMessage { get; set; }
public void AddMessage(string message)
{
Text = message;
OnMessage?.Invoke();
}
In the razor component, inject the Messenger. Also, you should set an event to the OnMessage property, and then call StateHasChanged in order to tell the view that it can update
@inject Messenger messenger
// rest of component here, and then the code block
protected override async Task OnInitializedAsync()
{
messenger.OnMessage += () =>
{
// do something with the messenger.Text here
InvokeAsync(this.StateHasChanged);
};
}
Don't forget, on your Startup class, add the class Messenger as a Singleton in order to have it available for injection
services.AddSingleton();
I hope that is what you were trying to achieve, and it can help others as well. Cheers.