How do I implement a Selector in Fluxor?

698 Views Asked by At

I am using Fluxor to manage state in my Blazor application and I have been unable to figure out the Selector part of the process.

I currently just inject the IState into my Razor Pages and get values from the State using State.Value.MyData

This works fine in a Razor Component that inherits from Fluxor.Blazor.Web.Components.FluxorComponent but doesn't work when getting a value in a class that is not a FluxorComponent. If I inject IState into a service class the state is not updated as changes are made. I can get around this by making transient services but I feel like I'm missing part of the puzzle here...

I think I need to use the Selector and SelectorProtocol but I have been unable to figure out how these parts are actually used in practice. Is there somewhere an example of how the Selector syntax is intended to be used?

1

There are 1 best solutions below

1
On BEST ANSWER

FluxorComponent is a convenience class that simply subscribes to all properties implementing IState<T> and calls StateHasChanged whenever one of them fires a StateChanged event.

You can achieve this yourself quite easily like so

@implements IDisposable

@code
{
  private IDisposable Subscription;
  [Inject] private IState<MyState> MyState { get; set; }

  protected override void OnInitialized()
  {
    base.OnInitialized(); // Does nothing, but good practice
    Subscription = StateSubscriber.Subscribe(this, _ => InvokeAsync(StateHasChanged));
  }

  void IDisposable.Dispose()
  {
    Subscription.Dispose();
  }
}