How does MessagingCenter work between classes?

MaruMaru DEMember ✭✭

Hi everyone,

I'm stuck at getting MessagingCenter working between classes. I only can get it to work in the same class. Can anyone point out an example how this works? I looked already at the documentation from Xamarin.

Best Answer

Answers

  • adamkempadamkemp USInsider, Developer Group Leader mod

    Can you show an example of what you are trying?

  • MaruMaru DEMember ✭✭
    edited August 2014

    @adamkemp‌ MessagingCenter stuff from Xamarin example.

    public class A
    {
        public void DoSomething()
        {
            MessagingCenter.Subscribe<B> (this, "Hi", (sender) => 
            {
                    // do something whenever the "Hi" message is sent
            });
        }
    }
    
    public class B
    {
        public void DoSomething()
        {
            MessagingCenter.Send<B> (this, "Hi");
        }
    }
    
  • adamkempadamkemp USInsider, Developer Group Leader mod

    When are you calling Subscribe and when are you calling Send? Is the object that is subscribing still around by the time the message is sent?

  • MaruMaru DEMember ✭✭

    One object is a Forms Page and the other one a normal object, both are still there.

  • CraigDunnCraigDunn USXamarin Team Xamurai
    edited August 2014

    As Adam asked, when are you calling the two DoSomething methods? Often the subscribe method is call in the constructor of a class, otherwise it won't be listening until the containing method is called. And also as he said, is the subscribing class still in memory when the message is sent? This is usually well-known for pages/screens, but other objects may be gone once they're no longer used.

    Maybe @JamesMontemagno‌'s post here will make it clearer, his explanation takes a different approach to the Xamarin doc?

Sign In or Register to comment.