假设我存在以下代码:
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;
}
}
我尝试将Rx应用于前端代码:
var observable = GetAllData(new[] { "1", "2", "3" }).ToObservable();
var subs = observable
.SubscribeOn(Scheduler.Default)
.Subscribe(
data => Console.WriteLine(data.Id),
() => Console.WriteLine("All Data Fetched Completed"));
它正常运作。
但是一旦我将订阅绑定到IObservable
,有什么方法可以阻止它继续中途获取数据?处理订阅不会停止枚举。
答案 0 :(得分:0)
嗯,一个简单的方法是:
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();