Created
June 1, 2023 19:19
-
-
Save maxkatz6/bd2caa21f8f27678b934c795b4d8b113 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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