C# 取消reactivex.net中的任务
假设我已经存在如下代码:C# 取消reactivex.net中的任务,c#,reactivex,C#,Reactivex,假设我已经存在如下代码: public IEnumerable<DataType> GetAllData(string[] ids) { foreach(var id in ids) { //this is a time-consuming operation, like query from database var data = this.repo.Find(id); yield return data; } }
public IEnumerable<DataType> GetAllData(string[] ids) {
foreach(var id in ids) {
//this is a time-consuming operation, like query from database
var data = this.repo.Find(id);
yield return data;
}
}
而且工作正常
但是,一旦我将订阅绑定到
IObservable
,是否有任何方法可以阻止它继续中途提取数据?Dispose订阅不会停止枚举。好的,一个简单的方法是:
var cts = new CancellationTokenSource();
var observable = GetAllData(new[] { "1", "2", "3" }).ToObservable().TakeWhile(x => !cts.IsCancellationRequested);
var subs = observable
.SubscribeOn(Scheduler.Default)
.Subscribe(
data => Console.WriteLine(data.Id),
() => Console.WriteLine("All Data Fetched Completed"));
//...
cts.Cancel();
var cts = new CancellationTokenSource();
var observable = GetAllData(new[] { "1", "2", "3" }).ToObservable().TakeWhile(x => !cts.IsCancellationRequested);
var subs = observable
.SubscribeOn(Scheduler.Default)
.Subscribe(
data => Console.WriteLine(data.Id),
() => Console.WriteLine("All Data Fetched Completed"));
//...
cts.Cancel();