In a MVVM based application if you decide to delegate all the communication to the infrastructure using abroker, so to respect the single responsibility principle, you end up dealing with problems that in a much more coupled environment would never arise.
Imagine the following scenario: As a user when I create e new order I need to choose the customer that owns the order so to successfully associate the order with the given customer.
In “programming” language the above translates to: when the user creates a new order and want to choose a customer we need toopen a search dialog to let the user search for the customer and thenreturn the chosen customer to the calling view.
I have highlighted the keywords in bold, we have 2 different contexts that needs to communicate but we do not want to have a direct relation between the 2 contexts, in other words: we do not want to open the dialog from the “create new order view model” but we want to delegate all the communication to the broker.
There are several options to achieve the same behavior but we think that the most important thing to avoid is to try to achieve the same “blocking” behavior that a dialog gives us because this prevents to move to a different UX without changing the implementation.
2-way messaging
The first viable approach is to use 2 messages where the first one is to request the start of the selection process and the second one is delivered by the selection process to send back the selection result(s):
class SelectCustomer { publicobject RequestToken{ get; set; } } class CustomerSelected { publicobject RequestToken{ get; set; } public IEnumerable<Customer> Selection{ get; set; } }
where the fact that we return a Task can be handy because can be used in conjunction with the async/await keywords and perfectly fit the async nature of the message broker broadcasting engine.