简体   繁体   English

可观察的取消令牌

[英]Cancellation token for observable

How can I cancel the following type of Rx Observable, if the following observable is being created on a StartButton click, ie from a stop button. 如果在StartButton单击上创建以下可观察对象,即从停止按钮创建,则如何取消以下类型的Rx Observable。

var instance = ThreadPoolScheduler.Instance; 

Observable.Interval(TimeSpan.FromSeconds(2), instance)
                     .Subscribe(_ =>
                     {
                     Console.WriteLine(DateTime.Now); // dummy event
                     }
                     );         

You retain the IDisposable that was returned by Subscribe , and call Dispose on it. 保留Subscribe返回的IDisposable ,并在其上调用Dispose

There may well be a way of integrating the Rx IDisposable -based unsubscription with CancellationToken out of the box, but just calling Dispose would be a start. 可能有一种方法可以将基于Rx IDisposable的取消订阅与CancellationToken开箱即用,但只是调用Dispose将是一个开始。 (You could always just register a continuation with the cancellation token to call dispose...) (您可以随时注册一个带取消令牌的续约来调用dispose ...)

Here's a short but complete example to demonstrate: 这是一个简短但完整的示例来演示:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var instance = ThreadPoolScheduler.Instance;
        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

        var disposable = Observable
            .Interval(TimeSpan.FromSeconds(0.5), instance)
            .Subscribe(_ => Console.WriteLine(DateTime.UtcNow));
        cts.Token.Register(() => disposable.Dispose());
        Thread.Sleep(10000);
    }
}

Just use one of the overloads of Subscribe that takes a CancellationToken : 只需使用带有CancellationTokenSubscribe的重载之一:

observable.Subscribe(_ => Console.WriteLine(DateTime.UtcNow), cancellationToken);

This simplifies Jon Skeet's example: 这简化了Jon Skeet的例子:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var instance = ThreadPoolScheduler.Instance;
        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

        Observable.Interval(TimeSpan.FromSeconds(0.5), instance)
            .Subscribe(_ => Console.WriteLine(DateTime.UtcNow), cts.Token);
        Thread.Sleep(10000);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM