【问题标题】:Rx.NET throttling with cancellationRx.NET 节流与取消
【发布时间】:2018-10-26 02:41:28
【问题描述】:

我有一个类似于this one 的问题。我需要通过以下方式处理一系列用户输入事件(搜索):

  • 用 N 毫秒限制每个搜索短语
  • 如果搜索短语发生更改,则取消之前运行的搜索(并且即将运行新搜索)
  • 仅应用最新搜索

除了取消之外,我的代码似乎几乎以这种方式工作。

Observable.FromEventPattern<TextChangedEventArgs>(
    handler => SearchBox.TextChanged += handler,
    handler => SearchBox.TextChanged -= handler)
.ObserveOn(SynchronizationContext.Current)
.Select(GetSearchQuery)
.Throttle(TimeSpan.FromMilliseconds(MinimumSearchIntervalMiliseconds))
.DistinctUntilChanged()
.Subscribe(ExecuteSearch, () => { });

string GetSearchQuery(EventPattern&lt;TextChangedEventArgs&gt;) 返回搜索字符串,void ExecuteSearch(string) 运行搜索。

由于某种原因,我在 SO 的所有答案中都找不到 Switch() 扩展名...

我在版本4.0.0中使用System.ReactiveSystem.Reactive.Linq

我猜这种形式的Select()Subscribe() 并不是上面代码中的最佳解决方案。他们可能应该在Tasks 上操作...

知道如何改进上述管道以支持根据需要取消吗?

【问题讨论】:

    标签: task-parallel-library system.reactive rx.net


    【解决方案1】:

    我在这里猜测,但您可能有ExecuteSearch 发送搜索字符串,获取结果,然后将它们绑定到 UI。拆分 ExecuteSearch 以返回理想的 IObservable&lt;Results&gt;Task&lt;Results&gt; 和一个新函数 public void ApplySearchResults(Results r) 来处理 UI 绑定。

    一旦你有了它,这应该可以工作:

    Observable.FromEventPattern<TextChangedEventArgs>(
        handler => SearchBox.TextChanged += handler,
        handler => SearchBox.TextChanged -= handler)
    .ObserveOn(SynchronizationContext.Current)
    .Select(GetSearchQuery)
    .Throttle(TimeSpan.FromMilliseconds(MinimumSearchIntervalMiliseconds))
    .DistinctUntilChanged()
    .Select(ExecuteSearch /* .ToObservable() if it returns Task<Results>/*)
    .Switch()
    .Subscribe(ApplyResults, () => { })
    

    .SwitchIObservable&lt;IObservable&lt;T&gt;&gt; 上工作。你没有双重可观察的,只有一个,这就是你没有看到它的原因。

    【讨论】:

    • 谢谢!这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多