With Rx, how do I ignore all-except-the-latest value when my Subscribe method is running

后端 未结 9 1566
暖寄归人
暖寄归人 2020-11-29 03:47

Using Reactive Extensions, I want to ignore messages coming from my event stream that occur while my Subscribe method is running. I.e. it sometimes takes me lon

9条回答
  •  -上瘾入骨i
    2020-11-29 04:01

    Here's a Task based implementation, with cancellation semantics, which doesn't use a subject. Calling dispose allows the subscribed action to cancel processing, if so desired.

        public static IDisposable SampleSubscribe(this IObservable observable, Action action)
        {
            var cancellation = new CancellationDisposable();
            var token = cancellation.Token;
            Task task = null;
    
            return new CompositeDisposable(
                cancellation,
                observable.Subscribe(value =>
                {
                    if (task == null || task.IsCompleted)
                        task = Task.Factory.StartNew(() => action(value, token), token);
                })
            );
        }
    

    Here's a simple test:

    Observable.Interval(TimeSpan.FromMilliseconds(150))
                          .SampleSubscribe((v, ct) =>
                          {   
                              //cbeck for cancellation, do work
                              for (int i = 0; i < 10 && !ct.IsCancellationRequested; i++)
                                  Thread.Sleep(100);
    
                              Console.WriteLine(v);
                          });
    

    The output:

    0
    7
    14
    21
    28
    35
    

提交回复
热议问题