I searched for a sample for this, but could not find something that explains clearly how to set it up using RX:
I have this requirement…
- In a WPF app, i have a list box
- A dispatcher timer routine adds some random numbers to a local List every say 2 seconds
- Now i want to setup an observable/observer to watch this List<int> as it keeps building up, and add the most recent number added, into the list box’s items collection.
Sounds very simple, and i have done the third bit in a background thread (no RX, but with a standard lookup on list<int>)and added to the listbox easily.
When trying to do the same without a background worker etc and just using RX, i am stuck.
Apologies for a possible stupid question (for you RX experts out there), but please help on how to get this WPF done using RX.
Thanks.
When working with Rx you need to keep in mind the duality between
IEnumerable<T>&IObservable<T>(as well asIEnumerator<T>&IObserver<T>).You should always look for objects that implement
IEnumerable<T>and consider how you would replace them withIObservable<T>.In your question you say that you have a timer adding some numbers to a
List<int>which you want to observe and add the new numbers to a list box. So I would consider replacing the list with anIObservable<int>. The trick here isn’t about watching a list (or anObservableCollection<int>) but instead it is about using Rx as a core part of your code.So, here’s a simple example.
Start with the core elements described in your question:
Create an observable from
dispatchTimer:Query the observable to create a new observable of random numbers:
Now, subscribe to the random numbers observable to update the list box:
The
.ObserveOnDispatcher()call will make sure that the numbers are added to the list box on the UI thread.You need to define a field or a property to hold a reference to the subscription so that it doesn’t get garbage collected. This is exactly what event handler fields do when you add a handler, but with Rx you must explicitly do it.
There you go – you now have a list box being updated from random numbers generated at the interval specified in the time.
It’s that simple. I hope this helps.