Subscribing to multiple events with same action

NamanVishnoiNamanVishnoi USMember ✭✭

Hi,

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

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

Can I achieve this in single line? The reason being we will have more models like M1, M2 and then we will adding the same type of subscription again.

Thanks

Answers

  • AVINASHREDDY.8328AVINASHREDDY.8328 USMember ✭✭
    edited June 2017

    I use common functions for this kind of stuff.

    In your case, write subscribe methods in separate class like below

    public class MessagineCenterServices
    {
    public void Send(string key)
    {
    MessagingCenter.Send(this, key);
    }
    public void SubscribeMessagineCenterServices(string key, Action action)
    {
    MessagingCenter.Subscribe(this, key, (sender) =>
    {
    Device.BeginInvokeOnMainThread(() =>
    {
    action?.Invoke();
    });
    });
    }

        public void UnsubscribeMessageServices(string key)
        {
            MessagingCenter.Unsubscribe<MessagineCenterServices>(this, key);
        }
    

    }

    As you see I have single place for all my MessagineCenter functions.
    This is just a sample.You can have overloads in same manner.

    Note: MessagineCenter does not work with static class

  • NamanVishnoiNamanVishnoi USMember ✭✭

    I found the answer. The message can be made very specific and the subscription can be done as:

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

Sign In or Register to comment.