Tuesday, February 2, 2010

Sharing ViewModel Data in a Decentralised Way

Yesterday I asked some colleagues to give me some constructive feedback on my last two posts about using an Observer pattern to share ViewModel data within a Prism Module. One comment was that it would be nice to have something sharing the data in a decentralised manner using Prism's EventAggregator.

This got me thinking that this sounded like a good idea. Eventually however I remembered that I'd considered this a while ago (but had subsequently forgotten about it, should have made an blog entry!) The reason I didn't pursue this approach for long was that I was concerned about how ViewModels would be initialised with the shared data values.

For example, imagine an application that has several ViewModels all using the EventAggregator to communicate to each other about changes in a shared piece of data. Imagine now that the user initiates an action that instantiates a new instance of another ViewModel to come online (for example, they have just clicked the Next button in a Wizard style workflow). How would this new ViewModel determine the current value of the shared data?

Try as I might, I couldn't see a nice way to do this. The ViewModel could raise an event asking what the value is, but then who should reply? Since the data has no "home" per se, there is no single definitive source that can supply an answer. Ultimately it would decsend into a pile of spaghetti for anything but the simplest of situations.

Now, this is not to say that there is not good way to do it. I just couldn't think of one. In the end, I like the Observer, as it gives the data a home, a place to live, which is nice.

No comments:

Post a Comment