开发者

new data to observable with each method invocation

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; 

    开发者_如何学Govoid 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?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜