将两个事件组合到IObservable中

时间:2013-11-03 14:52:55

标签: c# .net system.reactive

我有下一个界面:

public interface ITask
{
    event EventHandler<EventArgs> Completed;
    event EventHandler<UpdateEventArgs> Update;
}

我希望拥有IObservable,当ITask.Copdted事件触发时,会触发IOasker.OnNext,当ITask.Update事件触发时触发IObserver.OnCompleted。我可以使用RX实现这种组合,或者这是不可能的,我为此做了自定义实现。

2 个答案:

答案 0 :(得分:4)

像这样:

/* Assume you have an instance of ITask here */
ITask task;

var updates = Observable.FromEventPattern<UpdateEventArgs>(task, "Update");
var completed = Observable.FromEventPattern<EventArgs>(task, "Completed");

var desiredStream = updates.TakeUntil(completed);

/* example usage */
desiredStream.Subscribe(Console.WriteLine,
                        () => Console.WriteLine("Done"));

答案 1 :(得分:1)

这是一个人为的例子,它显示了在标准.NET事件上发布的5个“更新”,然后是一个包含标准事件的可观察序列,并在“完成”发生时结束。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class UpdateEventArgs : EventArgs
    {
        public string Value { get; set; }
    }
    public interface ITask
    {
        event EventHandler<EventArgs> Completed;
        event EventHandler<UpdateEventArgs> Update;
    }

    public partial class Form1 : Form, ITask
    {
        public event EventHandler<EventArgs> Completed;

        public event EventHandler<UpdateEventArgs> Update;

        private Timer m_timer = new Timer();

        private int m_timercount = 5;

        public Form1()
        {
            InitializeComponent();

            var obUpdate = Observable.FromEventPattern<UpdateEventArgs>(this, "Update");
            var obCompleted = Observable.FromEventPattern<EventArgs>(this, "Completed");

            var obUpdatesUntilCompletedSequence = obUpdate.TakeUntil(obCompleted);

            obUpdatesUntilCompletedSequence.Subscribe(new Action<EventPattern<UpdateEventArgs>>(UpdateOccurred), new Action(UpdateCompleted));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            m_timer.Interval = 1000;
            m_timer.Start();
            m_timer.Tick += m_timer_Tick;
        }

        void m_timer_Tick(object sender, EventArgs e)
        {
            Update(this, new UpdateEventArgs { Value = DateTime.Now.ToString() });

            if (--m_timercount == 0)
            {
                Completed(this, new EventArgs());

                m_timer.Stop();
            }
        }

        private void UpdateOccurred(EventPattern<UpdateEventArgs> update)
        {
            System.Diagnostics.Debug.WriteLine(update.EventArgs.Value);
        }

        private void UpdateCompleted()
        {
            System.Diagnostics.Debug.WriteLine("No more updated will be received");
        }
    }
}