如何使用ReactiveCommand对IObservable <t>进行采样

时间:2017-06-28 10:21:54

标签: c# system.reactive reactiveui

我有一个源可观察

Observable<T> source

和执行功能

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

我希望编写一个ReactiveCommand,在触发时使用最新的source值执行T.当没有值可用时,该命令不应该是可执行的

2 个答案:

答案 0 :(得分:2)

除非我误解,否则我认为行为主题和第一个价值观需要注意的事情要简单得多。

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);

答案 1 :(得分:1)

/// 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
      );