Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

android - 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);
    }
question from:https://stackoverflow.com/questions/65933018/xamarin-application-lifecycle-with-messagingcenter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...