If I have stream with a long running operation, something like:
inputStream.Select(n => Task.Run(() =>
{
// Long running operation
Thread.Sleep(TimeSpan.FromSeconds(5));
return n * n;
}).ToObservable())
.Switch()
.Subscribe(result =>
{
// Use result in some way
Console.WriteLine(result);
});
How can I get a CancellationToken inside of the Task.Run call so that when Switch disposes the subscription of an in-flight calculation, it sets the CancellationToken as cancelled so I know to abort the calculation.
You can use the
Observable.StartAsyncmethod, e.g.Alternatively, if you’ll be producing multiple values you can use the
Observable.Createoverload that works withTaskto get a CancellationToken. E.g.Inside of your task, you need to call
OnNextto produce values. The return value of the task, if any, is ignored.