【发布时间】:2014-06-08 14:38:53
【问题描述】:
我目前正在试验 ReactiveUI (5.5.1),并且我创建了一个 ViewModel(ReactiveObject 的子类),它可以作为 autocomplete 用于位置搜索(改编自mikebluestein/ReactiveUIDemo on github)。每次查询文本更改时,都会调用一个 REST 服务,该服务会为提交的查询返回匹配的位置。
问题:正如您在下面的代码中看到的,DoSearchAsync(string query, CancellationToken cancellationToken) 是可取消的,但是,我不确定如何(以及在代码中的何处)实际取消任何搜索 -因此使用CancellationToken.None atm。在这个特定的用例中取消请求似乎有点过头了,但我想知道在这个响应式 UI/异步任务场景中如何启用取消。
代码:
public class ReactiveLocationSearchViewModel : ReactiveObject {
readonly ReactiveCommand searchCommand = new ReactiveCommand();
public ReactiveCommand SearchCommand { get { return searchCommand; } }
string query;
public string Query
{
get { return query; }
set { this.RaiseAndSetIfChanged(ref query, value); }
}
public ReactiveList<Location> ReactiveData { get; protected set; }
public ReactiveLocationSearchViewModel()
{
ReactiveData = new ReactiveList<Location>();
var results = searchCommand.RegisterAsyncTask<List<Location>>(async _ => await DoSearchAsync(query, CancellationToken.None));
this.ObservableForProperty<ReactiveLocationSearchViewModel, string>("Query")
.Throttle(new TimeSpan(700))
.Select(x => x.Value).DistinctUntilChanged()
.Where(x => !String.IsNullOrWhiteSpace(x))
.Subscribe(searchCommand.Execute);
results.Subscribe(list =>
{
ReactiveData.Clear();
ReactiveData.AddRange(list);
});
}
private async Task<List<Location>> DoSearchAsync(string query, CancellationToken cancellationToken)
{
// create default empty list
var locations = new List<Location>();
// only search if query is not empty
if (!string.IsNullOrEmpty(query))
{
ILocationService service = ServiceContainer.Resolve<ILocationService>();
locations = await service.GetLocationsAsync(query, cancellationToken);
}
return locations;
}
}
【问题讨论】:
标签: c# mvvm reactiveui cancellation