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

后端 未结 9 1585
暖寄归人
暖寄归人 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条回答
  •  不知归路
    2020-11-29 03:50

    An example using Observable.Switch. It also handles the case when you complete the task but there is nothing in the queue.

    using System.Reactive.Linq;
    using System.Reactive.Subjects;
    using System.Reactive.Concurrency;
    using System.Reactive.Disposables;
    
    namespace System.Reactive
    {
        public static class RXX
        {
            public static IDisposable SubscribeWithoutOverlap
            ( this IObservable source
            , Action action
            , IScheduler scheduler = null)
            {
                var sampler = new Subject();
                scheduler = scheduler ?? Scheduler.Default;
                var p = source.Publish();
                var connection = p.Connect();
    
                var subscription = sampler.Select(x=>p.Take(1))
                    .Switch()
                    .ObserveOn(scheduler)
                    .Subscribe(l =>
                    {
                        action(l);
                        sampler.OnNext(Unit.Default);
                    });
    
                sampler.OnNext(Unit.Default);
    
                return new CompositeDisposable(connection, subscription);
            }
        }
    }
    

提交回复
热议问题