我正在使用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);
答案 0 :(得分:2)
以下是我将如何做到这一点 - 它有点棘手,因为实际的事件序列反馈回自身(即选择一个项目集SearchTerms)
// 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);