ReactiveUI/Reactive Extensions: 如何清除ObservableAsPropertyHelper

3

我正在使用ReactiveUI框架搜索全球机场列表。

我已经设置了ObservableAsPropertyHelper,它是ViewModel中SearchTerm属性的建议机场输出。以下是ObservableAsPropertyHelper的定义。在视图中,我有一个列表框绑定到这个属性。我希望能够显式地清除列表框(因为一旦用户选择了建议的项,我希望用所选的机场填充SearchTerm并清除建议列表)。是否有一种优雅的方法来实现这个?

var searchTerms = this.ObservableForProperty(x => x.SearchTerms).Where(x => canSearch).Value().Throttle(TimeSpan.FromMilliseconds(500));
var searchResults = searchTerms.SelectMany(SearchAirports);
var latestResults = searchTerms.CombineLatest(searchResults, (s, r) => r.SearchTerm != s ? null : r.AirportLiteWithWeights).Where(x => x != null);
_airportLiteWithWeights = latestResults.ToProperty(this, x => x.AirportLiteWithWeights);
1个回答

2

以下是我会如何做 - 这有点棘手,因为实际事件的顺序会反馈到自身(例如,选择一个项目会设置搜索词)

// The act of selecting an item is very ICommand'y, let's model it
// as such.
ReactiveCommand SuggestionItemSelected = new ReactiveCommand();

// Important to *not* signal a change here by touching the field
// so that we avoid a circular event chain
SuggestionItemSelected.Subscribe(x => _searchTerms = x);

// NB: Always provide a scheduler to Throttle!
var searchTerms = this.WhenAnyValue(x => x.SearchTerms)
    .Where(x => canSearch)
    .Throttle(TimeSpan.FromMilliseconds(500), RxApp.MainThreadScheduler);

// Select + Switch will do what you were trying to do with CombineLatest
var latestResults = searchTerms
    .Select(SearchAirports);
    .Switch()

// The listbox is the combination of *Either* the latest results, or the
// empty list if someone chooses an item
var latestResultsOrCleared = Observable.Merge(
    latestResults,
    SuggestionItemSelected.Select(_ => new List<Results>()));

latestResultsOrCleared
    .ToProperty(this, x => x.AirportLiteWithWeights, out _airportLiteWithWeights);

谢谢 Paul!但 _searchTerms = x 不会更新用户界面....顺便说一句,今天我学了些新东西。Switch() 方法确实适用于这种情况!谢谢! - icube
谢谢Paul,我能够使用这个解决方案。但是我正在使用RxUI 7,并且使用基本上是一个空命令来实现这个。在这个版本中是否有更优雅的解决方案,因为没有ReactiveCommand.Create();所以我正在使用this.CancelCommand = ReactiveCommand.Create(() => { }); - Saxar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接