0

假设我已经存在如下代码:

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,有什么办法可以阻止它继续中途获取数据?处置订阅不会停止枚举。

4

1 回答 1

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();

https://stackoverflow.com/a/31529841/2130786

于 2015-12-08T10:12:32.863 回答