每个方法调用都可以观察到的新数据

时间:2011-09-22 20:42:34

标签: c# system.reactive

这对于技术诀窍的人来说可能非常简单,但是无论何时调用我的方法,我如何直接向给定的observable提供新数据?

    IObservable<int> _myObservable; 

    void ThingsCallMe(int someImportantNumber)
    {
        // Current pseudo-code seeking to be replaced with something that would compile?
        _myObservable.Add(someImportantNumber);
    }

    void ISpyOnThings()
    {
        _myObservable.Subscribe(
            i =>
            Console.WriteLine("stole your number " + i.ToString()));
    }

我也不知道我应该使用什么样的可观察物,只能在特殊情况下进入OnCompleted()?

2 个答案:

答案 0 :(得分:3)

这是基本答案。我稍微修改了你的代码。

Subject<int> _myObservable = new Subject<int>(); 

void ThingsCallMe(int someImportantNumber)
{
    // Current pseudo-code seeking to be replaced with something that would compile?
    _myObservable.OnNext(someImportantNumber);
}

void ISpyOnThings()
{
    _myObservable.Subscribe(
        i =>
        Console.WriteLine("stole your number " + i.ToString()));
}

这应该有效。主题只是一个IObservable和一个IObserver。您可以调用OnCompleted,OnError等

答案 1 :(得分:0)

我测试过并且正常工作:

static ObservableCollection<int> myCol = new ObservableCollection<int>();

static void Main(string[] args)
{
  ((INotifyCollectionChanged)myCol).CollectionChanged += new NotifyCollectionChangedEventHandler(Program_CollectionChanged);

  ThingsCallMe(4);
  ThingsCallMe(14);
}

static void ThingsCallMe(int someImportantNumber)
{
    myCol.Add(someImportantNumber);
}

static void Program_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    Debug.WriteLine(e.NewItems.ToString());
}