2

我有两个 observables,它们每个都做不同的事情。如果他们的第一个流在某个时间间隔内接收到一些数据,我希望第二个流忽略它的输入,比如说 500 毫秒。我该怎么做呢?

var s1 = new Subject<string>();
var s2 = new Subject<string>();

s1.Subscribe(x => Debug.Write(x));                
//Subscribe something slightly different
s2.Subscribe(x => Debug.WriteLine(x));


s1.OnNext("foo");
Thread.Sleep(500);
s2.OnNext("bar");

/* Expected output:
    * foobar /r/n
    */

s1.OnNext("fizz");
s2.OnNext("buzz");
/* Expected output:
* fizz
*/

谢谢!

4

1 回答 1

4

这将在每次s1产生一个值时启动一个计时器。每当该计时器运行时,它将s2在计时器到期时取消订阅并重新订阅:

var delay = TimeSpan.FromMilliseconds(500);
var s2lowPriority = s1
    .Select(_ => Observable.Timer(delay).SelectMany(_ => s2))
    .StartWith(s2)
    .Switch();

s2lowPriority.Subscribe(x => Debug.WriteLine(x));
于 2013-11-07T17:50:47.497 回答