Skip to content

Instantly share code, notes, and snippets.

@maxkatz6
Created June 1, 2023 19:19
Show Gist options
  • Save maxkatz6/bd2caa21f8f27678b934c795b4d8b113 to your computer and use it in GitHub Desktop.
Save maxkatz6/bd2caa21f8f27678b934c795b4d8b113 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MyAssembly.ViewModels;
/// <summary>
/// Simple implementation of Interaction pattern from ReactiveUI framework.
/// https://www.reactiveui.net/docs/handbook/interactions/
/// </summary>
public sealed class Interaction<TInput, TOutput> : IDisposable, ICommand
{
private Func<TInput, Task<TOutput>>? _handler;
public Task<TOutput> Handle(TInput input)
{
if (_handler is null)
{
throw new InvalidOperationException("Handler wasn't registered");
}
return _handler(input);
}
public IDisposable RegisterHandler(Func<TInput, Task<TOutput>> handler)
{
if (_handler is not null)
{
throw new InvalidOperationException("Handler was already registered");
}
_handler = handler;
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
return this;
}
public void Dispose()
{
_handler = null;
}
public bool CanExecute(object? parameter) => _handler is not null;
public void Execute(object? parameter) => Handle((TInput?)parameter!);
public event EventHandler? CanExecuteChanged;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment