new data to observable with each method invocation

偶尔善良 提交于 2019-12-13 01:40:14

问题


this may be really simple to those in the know-how, but how can i directly provide new data to a given observable, whenever a method of mine is invoked?

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

i also dont know what kind of observable i should employ, one that gets to OnCompleted() under special circumstances only?


回答1:


Here's the basic answer. I modified your code slightly.

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

This should work. A subject is simply an IObservable and an IObserver. You can call OnCompleted, OnError, etc.




回答2:


I tested and got this working:

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


来源:https://stackoverflow.com/questions/7521254/new-data-to-observable-with-each-method-invocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!