问题
[ This question is regarding IObservable / Rx ]
Working Fixed Delay
var frequency = TimeSpan.FromMinutes(5);
Result.Delay(frequency).Subscribe(i => Debug.WriteLine("After Fixed Delay"));
Pseudo-Code for Variable Delay
Result.Delay(GetAsymptotingTime()).Subscribe(i => Debug.WriteLine("After Changing Delay"));
While the code for variable delay compiles it gets called only once, providing only the first value (essentially a fixed value).
- How could you subscribe with a dynamic delay in Reactive Extensions?
回答1:
I think this works:
source
.SelectMany(i => Observable.Timer(GetAsymptotingTime()).Select(_=>i))
If your delays are decreasing, the resulting stream may be in a different order to the original stream.
回答2:
Looks like there is a new overload of .Delay that allows this functionality within RX itself:
From http://blogs.msdn.com/b/rxteam/archive/2012/03/12/reactive-extensions-v2-0-beta-available-now.aspx :
var res = input.Delay(x => Observable.Timer(TimeSpan.FromSeconds(x.Length)));
Given the user input, it gets delays for a duration equal to the length of the input in seconds. Stated otherwise, the delay of each element can now be dependent on the data itself.
回答3:
May be I did not get the question right, but I've steped into it when I was searching a way to put same fixed delay between items, that are coming too fast. The previsous solution did not work for me, (RX 4.0) actionally the was no delay at all.
My solution is simple:
myObservable.Zip(Observable.Interval(TimeSpan.FromSeconds(1)), (a, _) => a)
I've used it when testing dynamic sequence like
using var d2 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }
.ToObservable()
.Zip(Observable.Interval(TimeSpan.FromSeconds(1)), (a, _) => a)
.Do(a => Log.Logger.Debug("b {a}", a))
.Subscribe();
回答4:
If you want to delay once then you can use Observable.Delay. I don't know what the type of Result is, so I'll assume it's an IObservable already, so, you can do something like:
var Result = Observable.Range(0, 10);
var frequency = TimeSpan.FromMilliseconds(1500);
var delay = Result.Delay(frequency);
delay.Subscribe(x => Debug.WriteLine(x));
来源:https://stackoverflow.com/questions/10071004/delay-function-to-postpone-iobservable-values-dynamically