取消在reactivex.net

时间:2015-12-08 08:24:04

标签: 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;
    }
}

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

1 个答案:

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

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