Previously I’ve blogged about how to perform event aggregation using Prism for the Windows Runtime. When a publisher invokes the PubSubEvent<TPayload> class’s Publish method the system will run all actions that have been registered by the PubSubEvent<TPayload> class’s Subscribe method. Subscribers can control how the actions run, and use weak references by default. Therefore registering a subscription action does not add a reference to the subscriber. For more info about event aggregation see Communicating between loosely coupled components in AdventureWorks Shopper.
In this blog post I’ll extend the sample app to include event subscription filtering, so that an event subscriber callback is only executed when a filter predicate returns true.
A subscriber may not need to handle every instance of a published event. In this case, the subscriber can use a Subscribe method overload that accepts a filter parameter. The filter parameter is of type System.Predicate<TPayload> and is executed when the event is published. If the filter predicate returns true the subscriber callback is executed.
The second subscription to the OrderPaidForEvent specifies a ThreadOption enumeration value, and a filter parameter. The ThreadOption.PublisherThread enumeration value specifies that the event should be received on the publisher’s thread. The filter parameter specifies that the IsStockLevelTooLow predicate will be used to filter the event when it’s published.
The overall effect is that when the number of items in stock in the warehouse drops below ten, the HandleOrderPaidForEventFiltered subscriber callback is executed, which sets the ShowWarning property to true. This modifies the UI to display a warning to the user that stock levels are low.
In this blog post I’ve demonstrated how to use Prism for the Windows Runtime to perform event subscription filtering. This is achieved by using a Subscribe method overload that accepts a filter parameter. If the filter predicate returns true, the subscriber callback is executed.
The sample app can be downloaded here.