强制刷新到Observable.Buffer c#

时间:2012-10-17 23:01:02

标签: c# c#-4.0 buffer system.reactive

有没有办法强制Observable.Buffer在缓冲时间结束前刷新?

在示例中:

mSubscription = mFluxObservable.Buffer(new TimeSpan(0, 0, 1, 30)).Subscribe(o => saver(o, iSessionId));

我想在1:30时段结束前刷新数据!

2 个答案:

答案 0 :(得分:9)

这对我有用:

var subject = new Subject<Unit>();
var closing = Observable
    .Timer(new TimeSpan(0, 0, 1, 30))
    .Select(x => Unit.Default);

var query =
    mFluxObservable
        .Buffer(() => Observable
            .Amb(subject, closing)
            .Take(1));

现在我只需要调用subject.OnNext(Unit.Default)来强制缓冲区刷新。冲洗后立即启动一个新的缓冲区。

答案 1 :(得分:3)

...和使用窗口基本相同的主体:

var bufferPeriod = TimeSpan.FromSeconds(1.5);
var source = Observable.Interval(TimeSpan.FromMilliseconds(100)).Take(50);

//source.Buffer(bufferPeriod).Dump();

var bufferFlush = new Subject<long>();//Or Subject<Unit>
source.Window(
        ()=>Observable.Merge(Observable.Timer(bufferPeriod), bufferFlush))
    .Select(window=>window.ToList())
    .Dump();

//Simulate calling flush.
Observable.Interval(TimeSpan.FromMilliseconds(1350)).Take(2).Subscribe(bufferFlush);