取消reactivex.net中的任务

本文关键字:任务 net reactivex 取消 | 更新日期: 2023-09-27 18:26:01

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

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

取消reactivex.net中的任务

好吧,一个简单的方法是:

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