Katana
Katana

Reputation: 421

Xamarin : Subscribing to multiple messages with same action

I have four view models M1, M2, M3, M4 from where I am sending a message to another view model M5. M5 performs same action when it receives a message from any of them. Currently, I have written code in M5 like this:

MessgingCenter.Subscribe<M1, string>(this, "abc", () => { DoSomething(); });
MessagingCenter.Subscribe<M2, string>(this, "abc", () => { DoSomething(); });
MessgingCenter.Subscribe<M3, string>(this, "abc", () => { DoSomething(); });
MessagingCenter.Subscribe<M4, string>(this, "abc", () => { DoSomething(); });

Can I achieve this in single line?

Upvotes: 1

Views: 822

Answers (2)

hvaughan3
hvaughan3

Reputation: 11105

Using hugo's method is preferred but if nothing else fits, you can also simply make the subscriber into a string. You just need to be careful doing it this way because it is easy for multiple subscribers to start getting triggered from the same send.

MessagingCenter.Subscribe<string>(this , "abc", somethingString  => { DoSomething(somethingString); });

Then...

MessagingCenter.Send("something", "abc");

Edit: Adding interface code example mentioned in hugo's answer:

public interface IDoSomething { } //Does not necessarily have to have anything in it

public class ViewModelA : IDoSomething { }

public class ViewModelB : IDoSomething { }

MessagingCenter.Subscribe<IDoSomething, string>(this, "abc", () => { DoSomething(); }); //IDoSomething works the same as deriving from a base class in this instance

Upvotes: 1

hugo
hugo

Reputation: 1859

You can inherit M1, M2, M3, M4 from the same parent ViewModel (or interface) with a name such as "BaseViewModel" and then write:

MessagingCenter.Subscribe<BaseViewModel, string>(this, "abc", () => { DoSomething(); });

Upvotes: 2

Related Questions