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

后端 未结 9 1584
暖寄归人
暖寄归人 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:59

    Here is an attempt using "just" Rx. The timer and the subscriber are kept independent by observing on the threadpool and I've used a subject to provide feedback on completing the task.

    I don't think this is a simple solution, but I hope it might give you ideas for improvement.

    messages.
        Buffer(() => feedback).
        Select(l => l.LastOrDefault()).
        ObserveOn(Scheduler.ThreadPool).
        Subscribe(n =>
        {
            Thread.Sleep(TimeSpan.FromMilliseconds(250));
            Console.WriteLine(n);
            feedback.OnNext(Unit.Default);
        });
    
    feedback.OnNext(Unit.Default);
    

    There is one slight problem -- the buffer is first closed when it's empty so it generates the default value. You could probably solve it by doing the feedback after the first message.


    Here it is as an extension function:

    public static IDisposable SubscribeWithoutOverlap(this IObservable source, Action action)
    {
        var feedback = new Subject();
    
        var sub = source.
            Buffer(() => feedback).
            ObserveOn(Scheduler.ThreadPool).
            Subscribe(l =>
            {
                action(l.LastOrDefault());
                feedback.OnNext(Unit.Default);
            });
    
        feedback.OnNext(Unit.Default);
    
        return sub;
    }
    

    And usage:

        messages.SubscribeWithoutOverlap(n =>
        {
            Thread.Sleep(1000);
            Console.WriteLine(n);
        });
    

提交回复
热议问题