与接收值之间 [英] Between values with Rx

查看:155
本文介绍了与接收值之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有接收一些推广方法做下面的场景?

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

我有一个值,启动抽(绿圈)等超值停止抽(芦苇圆),蓝色圆圈应该是预期值,我不希望这个命令被取消并重新创建(即 TakeUntil和SkipUntil将无法正常工作)。

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).

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

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

怎么会是相同的逻辑的IObservable&LT; T&GT;

推荐答案

下面是你需要作为扩展方式:

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.

这篇关于与接收值之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆