I’m using the MVVM design pattern in my application which is comprised of,
- A Xamarin.IOs project (View Layer)
- A Net Standard project (Common Layer)
- A Xamarin.Android project (in the future) (View Layer)
In the Xamarin.IOs project, there’s a Delegate class (NotificationCenterDelegate
extending UNUserNotificationCenterDelegate
) which triggers a method (WillPresentNotification
) on receiving a notification. This method should inform a ViewModel (BasePageViewModel
) that the method was invoked. The BasePageViewModel
is not injected to the Delegate class.
There’s a couple of approaches I can use here,
-
Inject a ViewModel (
ControlViewModel
). Then invoke a method in the ViewModel from theWillPresentNotification
method.public void WillPresentNotification(/* parameters */) { ControlViewModel.UpdateCount(); }
In
ControlViewModel
I invoke an event that is captured and handled inBasePageViewModel
-
Implement an Interface (
IDelegateViewService
) in the Delegate class that has an Event Handler. Trigger the event in theWillPresentNotification
method.public class NotificationCenterDelegate : UNUserNotificationCenterDelegate, INotificationCenterDelegate { public void WillPresentNotification(/* parameters */) { CountUpdated?.Invoke(this, null); } } public interface IDelegateViewService { event EventHandler CountUpdated; }
Then capture handle the event in the
BasePageViewModel
.
I prefer the first approach as it doesn’t use an interface to invoke something in the ViewModel. Because as I feel using ViewServices reduces the ability of sharing code among different platforms. And I feel ViewServices should be only used if it’s the only approach available.
Can anyone comment on these two design approaches? I would like to get some theory involving why one is better than the other or why a completely different design is much better!