J. Lennon
J. Lennon

Reputation: 3361

Between values with Rx

Is there some extension method in Rx to do the scenario below?

Between values

I have a value to start the pumping (green circles) and other value to stop the pumping (reed circles), the blue circles should be the expected values, I would not want this command to be canceled and recreated (ie "TakeUntil" and "SkipUntil" will not work).

The implementation using LINQ would be something like this:

  public static IEnumerable<T> TakeBetween<T>(this IEnumerable<T> source, Func<T, bool> entry, Func<T, bool> exit)
    {
        bool yield = false;
        foreach (var item in source)
        {
            if (!yield)
            {
                if (!entry(item)) 
                    continue;

                yield = true;
                continue;
            }

            if (exit(item))
            {
                yield = false;
                continue;
            }

            yield return item;
        }
    }

How could this same logic for IObservable<T> ?

Upvotes: 3

Views: 159

Answers (2)

Enigmativity
Enigmativity

Reputation: 117029

Here's what you need as an extension method:

public static IObservable<T> TakeBetween<T>(
    this IObservable<T> source,
    Func<T, bool> entry,
    Func<T, bool> exit)
{
    return source
        .Publish(xs =>
        {
            var entries = xs.Where(entry);
            var exits = xs.Where(exit);
            return xs.Window(entries, x => exits);
        })
        .Switch();
}

The key thing I've included in this is the used of the Publish extension. In this particular case it is important as your source observable may be "hot" and this enables the source values to be shared without creating multiple subscriptions to the source.

Upvotes: 3

Brandon
Brandon

Reputation: 39182

I think you can use Window:

source.Window(entrySignal, _ => exitSignal).Switch();

Upvotes: 3

Related Questions