Serve Laurijssen
Serve Laurijssen

Reputation: 9763

Xamarin application lifecycle with MessagingCenter

In this Xamarin Activity a MessagingCenter Subscribe is done during OnCreate and Unsubscribe during OnDestroy. When the app loads it Subscribes and when pressing back button OnDestroy is called after OnBackPressed. So the cycle seems correct. However, every time back is pressed and the app is started again the registered function retrieveSorterScan is called an extra time. After 10 times restarting it is called 10 times even though unsubscribe / subscribe is called. I think it boils down to the following combination of functions. What could be wrong here?

edit after removing OnBackPressed it has the same behaviour so thats not the issue.

[Activity(Label = "RopsSorterApp", Icon = "@drawable/icon", Theme = "@style/MainTheme", LaunchMode = LaunchMode.SingleTask, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {

    protected override void OnCreate(Bundle bundle)
    {            
        base.OnCreate(bundle);
        Forms.Init(this, bundle);            
        Instance = this;

        app = new App();
        LoadApplication(app);

        MessagingCenter.Instance.Subscribe<Forms.Application, SorterScan>(Forms.Application.Current, INFO, app.MainPage.retrieveSorterScan);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        MessagingCenter.Instance.Unsubscribe<Forms.Application, string>(Forms.Application.Current, INFO);
    }

Upvotes: 0

Views: 124

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

In your case you passed two different type of parameters in Subscribe and Unsubscribe . So they are two different messages . The message that you Subscribe in OnCreate will never been Unsubscribe .

So you just modify it like following

MessagingCenter.Instance.Unsubscribe<Forms.Application, SorterScan>(Forms.Application.Current, INFO);

Upvotes: 3

Related Questions