3

Rx 中是否有一些扩展方法来执行以下场景?

值之间

我有一个值来开始抽水(绿色圆圈)和其他值来停止抽水(芦苇圈),蓝色圆圈应该是预期值,我不希望这个命令被取消和重新创建(即“TakeUntil”和“SkipUntil”将不起作用)。

使用 LINQ 的实现将是这样的:

  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;
        }
    }

怎么会有同样的逻辑IObservable<T>呢?

4

2 回答 2

3

这是您需要的扩展方法:

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();
}

我在其中包含的关键是Publish扩展的使用。在这种特殊情况下,它很重要,因为您的源 observable 可能是“热的”,这使得源值可以在不创建对源的多个订阅的情况下共享。

于 2013-09-16T05:23:15.367 回答
3

我认为您可以使用Window

source.Window(entrySignal, _ => exitSignal).Switch();
于 2013-09-13T20:02:41.063 回答