I have a class which takes in a stream of events, and pushes out another stream of events.
All of the events use Reactive Extensions (RX). The incoming stream of events is pushed from an external source into an IObserver<T>
using .OnNext
, and the outgoing stream of events is pushed out using IObservable<T>
and .Subscribe
. I am using Subject<T>
to manage this, behind the scenes.
I am wondering what techniques there are in RX to pause the output temporarily. This would mean that incoming events would build up in an internal queue, and when they are unpaused, the events would flow out again.
Here is my solution using Buffer and Window operators:
Window is opened at subscription and every time 'true' is received from pauser stream. It closes when pauser provides 'false' value.
Buffer does what it supposed to do, buffers values that are between 'false' and 'true' from pauser. Once Buffer receives 'true' it outputs IList of values that are instantly streamed all at once.
DotNetFiddle link: https://dotnetfiddle.net/vGU5dJ
Here's a reasonably simple Rx way to do what you want. I've created an extension method called
Pausable
that takes a source observable and a second observable ofboolean
that pauses or resumes the observable.It can be used like this:
Now, the only thing I couldn't quite work out what you mean by your "incoming stream of events is an
IObserver<T>
". Streams areIObservable<T>
. Observers aren't streams. It sounds like you're not doing something right here. Can you add to your question and explain further please?You can simulate pausing/unpausing with an
Observable
.Once your pauseObservable emits a 'paused' value, buffer events until pauseObservable emits an 'unpaused' value.
Here's an example which uses BufferUntil implementation by Dave Sexton and Observable logic by Timothy Shields (from my own question a while back)
Room for improvement : maybe merge the two subscriptions to source (pausedEvents and notPausedEvents) as one.