Between values with Rx

主宰稳场 提交于 2019-12-08 01:10:58

问题


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

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> ?


回答1:


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.




回答2:


I think you can use Window:

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


来源:https://stackoverflow.com/questions/18791622/between-values-with-rx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!