I’m coding an MVVM Silverlight application with MVVMLight. I was asking myself what is the best way to communicate between the Model and the ViewModel. My Model has asynchronous calls from a web service and I don’t know what is the best way to get the return value.
I’ve tried this:
public static void ModifySomething(Something s)
{
var c = MyServiceFactory.GetService();
c.ModifySomethingCompleted += (sender, e) =>
{
if (e.Error != null)
{
Messenger.Default.Send(new XyzException(e.Error, "ModifyError"));
return;
}
Messenger.Default.Send(e.Result, "ModifyOk");
};
c.ModifySomethingAsync(s);
}
and this:
public static void ModifySomething(Something s, Action<Something, Exception> callback)
{
var c = ServiceFactory.RecupererService();
c.ModifySomethingCompleted += (sender, e) =>
{
if (callback != null) callback(e.Result, e.Error);
};
c.ModifySomethingAsync(s);
}
Both works, in the first example I’m using the MvvmLight Messenger, so I have to register a list of string messages for every methods of my model, and then any ViewModel can hook to this action.
In the second example, I use the classic approach to send a callback which is fired on the Completed event. Only one callback is fired, but the code is much more readable.
What is the best approach ?
I would say: Depends on! Seriously! It depends on
I like the first approach because it gives me a service-bus-like behaviour and I can use configuration if I want to. The second one is more specific in terms of type-safety because you could make errors posting the messages.