我是Rx的新手所以请耐心等待。
我想在Task<T>
中包含IObservable<T>
。到目前为止一切顺利:
Task<T> task = Task.Factory.StartNew(...);
IObservable<T> obs = task.ToObservable();
现在,我想要的是在观察者取消订阅时发出取消信号:
var cancel = new CancellationToken();
Task<T> task = Task.Factory.StartNew(..., cancel);
IObservable<T> obs = task.ToObservable(); //there should be a way to tie the cancel token
//to the IObservable (?)
IDisposable disposable = obs.Subscribe(...);
Thread.Sleep(1000);
disposable.Dispose(); // this should signal the task to cancel
我该怎么做?
FWIW这里是生成此切线的场景:Rx and tasks - cancel running task when new task is spawned?
答案 0 :(得分:2)
这是我能想到的最简单的方法,使用Observable.Create
:
static IObservable<int> SomeRxWork()
{
return Observable.Create<int>(o =>
{
CancellationTokenSource cts = new CancellationTokenSource();
IDisposable sub = SomeAsyncWork(cts.Token).ToObservable().Subscribe(o);
return new CompositeDisposable(sub, new CancellationDisposable(cts));
});
}
static Task<int> SomeAsyncWork(CancellationToken token);
我在评论中暗示的最初方式实际上相当冗长:
static IObservable<int> SomeRxWork()
{
return Observable.Create<int>(async (o, token) =>
{
try
{
o.OnNext(await SomeAsyncWork(token));
o.OnCompleted();
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
o.OnError(ex);
}
});
}
答案 1 :(得分:2)
假设您有这样的方法:
Task<Gizmo> GetGizmoAsync(int id, CancellationToken cancellationToken);
您可以将其转换为IObservable<Gizmo>
,其中订阅会启动Task<Gizmo>
,取消订阅会使用以下内容取消订阅。
IObservable<Gizmo> observable = Observable.FromAsync(
cancellationToken => GetGizmoAsync(7, cancellationToken));
// Starts the task:
IDisposable subscription = observable.Subscribe(...);
// Cancels the task if it is still running:
subscription.Dispose();