如何阻止RX流中的事件发生?

时间:2014-08-19 13:56:40

标签: c# .net system.reactive reactive-programming

使用Microsoft Reavtive Extensions(RX),我想知道在事件发生之前是否可以阻止它?

像这样:

observableStream.BlockUntilTrue(o => o.MyProperty == true);

我尝试了什么

我已尝试observableStream.TakeUntil(o => o.MyProperty == true);,但会立即退出。

2 个答案:

答案 0 :(得分:5)

我在阅读你的评论后重写了我的回答。在您的情况下,您可以使用First但它会将RX的异步性质更改为阻塞的同步代码。我想这就是你的问题。

var firstValue = observableStream.
  .Where(o => o.MyProperty)
  .First();

First的调用将阻止并等待第一个值从可观察序列到达,这似乎是你想要的。

答案 1 :(得分:0)

此演示代码效果很好。它添加了一个阻塞的扩展方法,直到流上发生单个事件。如果为BlockingCollection的Take()添加了超时,它将等到事件发生或发生超时。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RX_2
{
    public static class Program
    {
        static void Main(string[] args)
        {
            Subject<bool> stream = new Subject<bool>();

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 4; i++)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(500));
                        stream.OnNext(false);
                    }
                    stream.OnNext(true);
                });

            Console.Write("Start\n");
            stream.Where(o => o == true).BlockUntilEvent();
            Console.Write("Stop\n");
            Console.ReadKey();
        }

        public static void BlockUntilEvent(this IObservable<bool> stream)
        {
            BlockingCollection<bool> blockingCollection = new BlockingCollection<bool>();
            stream.Subscribe(blockingCollection.Add);
            var result = blockingCollection.Take();
        }
    }
}
相关问题