0

I have a ReactiveObject with a Property "A" of type "ReactiveList".

In my ViewModel I'd like to sum a property of "T" of every item in my list. I got it working, while "A" not changes its value.

But all gets "out of sync", when I assign a new value to "A" (e.g. this.A = new ReactiveList();).

Does anyone have an idea how to solve this? I hope I explained my problem clear enough.

x-ray
  • 1
  • 1
    It might be helpful to supply a code sample if you have one. People here are good at dissecting code. – RacerNerd Feb 27 '14 at 01:10

2 Answers2

1

Instead of listening to A directly, listen to this:

this.WhenAnyObservable(x => x.A.ItemsChanged).Subscribe(...);

Whenever A changes, you'll resubscribe to A. Now, knowing when to reset to do a Sum, that's a bit more tricky. Here's the lazy yet more fool-proof way to do this:

Observable.Merge(
    this.WhenAny(x => x.A, _ => Unit.Default),
    this.WhenAnyObservable(x => x.Changed).Select(_ => Unit.Default))
.Select(_ => this.A.Sum(x => x.SomePropOnTheItem))
.DistinctUntilChanged()
.Subscribe(x => Console.WriteLine("Latest sum is {0}", x);
Ana Betts
  • 73,868
  • 16
  • 141
  • 209
1

1 - I'd avoid assigning new Collections continuously as part of your logic, and rather use Clear(). Which should have the same impact in terms of GC.

2- If absolutely necessary, utilize a SerialDisposable and subsribe on the main object A

this.ObservableForProperty(p=> p.A).Subscribe(newAvalue=>{
   someSerialDisposable.Disposable=
        newAvalue.Changed.Subscribe(_=>this.Result=this.A.Sum(x=>x.T))
});

This would dispose previous deep subscriptions on A instances.

WeSam Abdallah
  • 1,050
  • 1
  • 10
  • 16