【问题标题】:Ignore events if another event fires with Rx [duplicate]如果使用 Rx 触发另一个事件,则忽略事件 [重复]
【发布时间】:2016-03-28 08:35:25
【问题描述】:

总之

寻找实现的方法

observableOne.SkipIf(observableTwoFiresWithinPeriod)

说明

  • 假设我正在观察人们穿过一扇门 (walkins Observable)
  • 而且我也有办法判断他们是否有电话 (phoneWalkins Observable)。
  • 现在我想观察一下人们不带手机走进门的另一块蛋糕 (nonPhoneWalkins Observable)

假设我有walkins 和phoneWalkins 子集作为流可供我使用,那么nonPhoneWalkins 应该是walkins,除了phoneWalkins。

  • 如何使用响应式扩展来实现它?
  • 请注意,如果发现此人携带手机,phoneWalkins 会在 walkins 之后发出信号

【问题讨论】:

  • 您可以将@LeeCampbell 的解决方案应用于此问题。只需省略 Where 子句即可。

标签: c# .net linq event-handling system.reactive


【解决方案1】:

这是我的简单尝试:

public class Program
    {
        static void Main()
        {
            // all walkins
            var walkins =
                // all persons through a door each second
                Observable.Interval(TimeSpan.FromSeconds(1), Scheduler.CurrentThread)
                // if has phone (is even) then true, if not false
                .Select(i => (i % 2 == 0));

            var phoneWalkins = // substream of phoneWalkins (if you want it separate)
                walkins
                .Where(i => (i == true))
                .Select(i => i);

            var nonPhoneWalkins = // substream of nonPhoneWalkins (if want it separate)
                walkins
                .Where(i => (i == false))
                .Select(i => i);

            //walkins.Subscribe(Console.WriteLine); // output all
            phoneWalkins.Subscribe(Console.WriteLine); // output phone
            //nonPhoneWalkins.Subscribe(Console.WriteLine); // output nonPhone
        }
    }

【讨论】:

  • 不幸的是,情况并非如此,我的意思是 phoneWalkins 和 nonPhoneWalkins 不能直接从 walkin 派生,即 phoneWalkins 是一个独立的测量源,例如Bob 被雇来统计携带手机走进来的人数,但闭路电视摄像机不加区别地统计走进来的人数
【解决方案2】:

感谢@supertopi 指出另一个相关问题,@LeeCampbell 的答案移植到这个上下文应该有效:

nonPhoneWalkins = 
    walkins.SelectMany
    (walkin => 
        phoneWalkins.Take(1).Select(phoneWalkin => false)
        .Amb(
            Observable.Timer(TimeSpan.FromSeconds(1)).Select(l => true)
            )
    )
    .Where(nonPhoneWalkin => nonPhoneWalkin);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    相关资源
    最近更新 更多