马邦德
马邦德

Reputation: 103

how to create observable from blazor element's click events

@* test.razor *@

<button>click</button>

I have a button in a razor component, and I want to create an Observable from it's click event which I don't know how to do. Can anyone help me ?

Upvotes: 2

Views: 2912

Answers (1)

Lee McPherson
Lee McPherson

Reputation: 931

You could use ReactiveUI (on Nuget).

C# ViewModel constructor

public class MyViewModel : ReactiveObject
{
   public ReactiveCommand<Unit,Unit> MyCommand {get;}

   public MyViewModel()
   {
       MyCommand = ReactiveCommand.Create((_)=> // do some work);
   }
}

MyComponent.razor

@inherits ReactiveComponentBase<MyViewModel>

<button @onclick=@(()=> ViewModel.MyCommand.Execute().Subscribe() )>click</button>

OR

If you refuse to use ReactiveUI (it's good!), you can make your own subject. Just make sure you dispose of everything properly.

MyComponent.razor

<button @onclick=@(()=> command.OnNext(Unit.Default) )>click</button>

@code{
   private Subject<Unit> command = new Subject<Unit>();
   public IObservable<Unit> Command => command.AsObservable();
}

If there were an event to handle like in regular C# based UI, then we could use the Observable.FromEvent pattern, but Blazor doesn't do events like this. UIs built with C# (UWP, Xamarin) use the command pattern instead. This is why there is a ReactiveCommand in ReactiveUI. A UI button will generally understand how to deal with something that implements ICommand which gives it the ability to disable itself when the command is inactive. (i.e. when you haven't finished processing the command) Not many Blazor components can deal with ICommand directly yet, but you can manually have it work with them. BlazorFluentUI has buttons that work with Commands. (This is the component library I work on.)

Upvotes: 3

Related Questions