如何使用<T>反应式命令对 IObservable 进行采样



我有一个源可观察

Observable<T> source

和执行功能

void Execute(T t){
    ....
}

我想编写一个eacterivecommand,该veactivecommand在触发时用最新的源值执行t。当没有值可用时,该命令不应执行

,除非我误会了,否则我认为行为主题可能会更简单,并且要注意一个第一个值。

var source = Observable.Interval(TimeSpan.FromSeconds(4));
var subject = new BehaviorSubject<long>(0L);
source.Subscribe(subject);
var canExecute = source.Select(_ => true).StartWith(false);
ICommand command = ReactiveCommand.Create(() => Execute(subject.Value), canExecute);
/// Create a ReactiveCommand that samples a source observable. The
/// source is immediately subscribed to so that when the command
/// is executed the previous value is available to the execution
/// function.
public static ReactiveCommand<Unit,Unit> CreateCommand<T>
    (this IObservable<T> source
     , Action<T> execute
     , IObservable<bool> canExecute)
{
    var so = source.Replay(1).RefCount();
    return ReactiveCommand.CreateFromTask
        ( async () => execute( await so.FirstAsync() )
          , canExecute.Merge( so.Select( _ => true ).StartWith( true ) ));
}

用法

IObservable<int> dataSource = ...;
IObservable<bool> canExecute = ...;
ReactiveCommand command = ReactiveCommandCreate
      ( dataSource
      , value => Console.WriteLine(value)
      , canExecute
      ); 

相关内容

  • 没有找到相关文章

最新更新