using System; using System.Reactive.Disposables; using System.Reactive.Linq; namespace Avalonia.Interactivity { /// /// Provides extension methods for the interface. /// public static class InteractiveExtensions { /// /// Adds a handler for the specified routed event and returns a disposable that can terminate the event subscription. /// /// The type of the event's args. /// Target for adding given event handler. /// The routed event. /// The handler. /// The routing strategies to listen to. /// Whether handled events should also be listened for. /// A disposable that terminates the event subscription. public static IDisposable AddDisposableHandler(this IInteractive o, RoutedEvent routedEvent, EventHandler handler, RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble, bool handledEventsToo = false) where TEventArgs : RoutedEventArgs { o.AddHandler(routedEvent, handler, routes, handledEventsToo); return Disposable.Create( (instance: o, handler, routedEvent), state => state.instance.RemoveHandler(state.routedEvent, state.handler)); } /// /// Gets an observable for a . /// /// The object to listen for events on. /// The routed event. /// The routing strategies to listen to. /// Whether handled events should also be listened for. /// /// An observable which fires each time the event is raised. /// public static IObservable GetObservable( this IInteractive o, RoutedEvent routedEvent, RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble, bool handledEventsToo = false) where TEventArgs : RoutedEventArgs { o = o ?? throw new ArgumentNullException(nameof(o)); routedEvent = routedEvent ?? throw new ArgumentNullException(nameof(routedEvent)); return Observable.Create(x => o.AddDisposableHandler( routedEvent, (_, e) => x.OnNext(e), routes, handledEventsToo)); } } }