Is it okay to have a MessageCenter Subscribe in a page constructor?

I'm subscribing to a MessageCenter message in a page constructor as I want it to change the page even before the page has appeared:

    public PhrasesFrame()
    {
        InitializeComponent();
        vm = new PhrasesFrameViewModel();
        BindingContext = vm;
        vm.Theme = Settings.th.ToString();
        MessagingCenter.Subscribe<SettingsPage>(this, "ThemeChanged", (sender) => {
            vm.Theme = Settings.th.ToString();
        });
    }

The PhrasesFrame is only created one time in my application as it's one of the tabs.

Is there any issue with Subscribing here. The reason I ask is I would not have an UnSubscribe or at least I don't know where to put one.

1 answer

  • answered 2018-11-08 08:29 Gerald Versluis

    You're already answering your own question basically. You can, of course, subscribe here. But you will need to find a point in your page/app's lifecycle to unsubscribe. Else, this page might be alive forever, leaking memory, while that is not what you want.

    A better option might be to subscribe whenever it appears and unsubscribe when it disappears as suggested in the comments. Is there any reason not to do that?

    You could also subscribe in the constructor and unsubscribe in the disappearing, but then the subscribe event will never happen again if the page is only instantiated once.

    Long answer short; you will want to unsubscribe. So as long as you can cover that and make it work with your requirements, subscribing in your constructor is fine.