How to throttle event stream using RX?

前端 未结 8 794
终归单人心
终归单人心 2020-11-27 04:04

I want to effectively throttle an event stream, so that my delegate is called when the first event is received but then not for 1 second if subsequent events are received. A

8条回答
  •  长情又很酷
    2020-11-27 04:20

    Ok, here's one solution. I don't like it, particularly, but... oh well.

    Hat tips to Jon for pointing me at SkipWhile, and to cRichter for the BufferWithTime. Thanks guys.

    static void Main(string[] args)
    {
        Console.WriteLine("Running...");
    
        var generator = Observable
            .GenerateWithTime(1, x => x <= 100, x => x, x => TimeSpan.FromMilliseconds(1), x => x + 1)
            .Timestamp();
    
        var bufferedAtOneSec = generator.BufferWithTime(TimeSpan.FromSeconds(1));
    
        var action = new Action>(
            feed => Console.WriteLine("Observed {0:000}, generated at {1}, observed at {2}",
                                      feed.Value,
                                      feed.Timestamp.ToString("mm:ss.fff"),
                                      DateTime.Now.ToString("mm:ss.fff")));
    
        var reactImmediately = true;
        bufferedAtOneSec.Subscribe(list =>
                                       {
                                           if (list.Count == 0)
                                           {
                                               reactImmediately = true;
                                           }
                                           else
                                           {
                                               action(list.Last());
                                           }
                                       });
        generator
            .SkipWhile(item => reactImmediately == false)
            .Subscribe(feed =>
                           {
                               if(reactImmediately)
                               {
                                   reactImmediately = false;
                                   action(feed);
                               }
                           });
    
        Console.ReadKey();
    }
    

提交回复
热议问题