How delete past events of a page when leaving it with PopAsync ?

asierdoasierdo Member ✭✭

Hi everybody,
I call MyPage with Navigation.PushAsync() from the MainPage. I have next code in MyPage's constructor:

    public MyPage(IAdapter adapterin, IDevice devicein, string ChannelName)
    {
        InitializeComponent();
        adapter = adapterin;
        device = devicein;
        LabelChannelName.Text = ChannelName;

        adapter.DeviceConnectionLost += (s, e) =>
        {
            Debug.WriteLine($"LOST CONNECTION: {e.Device.Name}");
            adapter.DeviceConnectionLost -= null;
            Device.BeginInvokeOnMainThread(() =>
            {
                this.Navigation.PopAsync();
            });
            Debug.WriteLine($"LOST CONNECTION.");
        };
    }

When adapter.DeviceConnectionLost happens (for instance when I shut dowm my ble peripheral) MyPage closes correctly.
The second time I open MyPage if DeviceConnectionLost event happens then I get an Unhandled Exception, cause I guess PopAsync is reached twice. It seems that second PopAsync() generates the exception.

I have checked that if MyPage is loaded three times for example, ConnectionLost event will be executed three times, as I can see "LOST CONNECTION." text in my debug output window.

Is there any way to erase past events of MyPage after doing PopAsync ? How could I resolve this issue ?

Thanks in advance and best regards,
Asier.

Best Answer

Answers

  • ShantimohanElchuriShantimohanElchuri USMember ✭✭✭✭✭

    @asierdo Note that such inline deligates are the main source of memory leaks which lead to instability. Though they are very easy to code, especially when they are short, not preferred. Otherwise, wherever you do a PopAsync(), the protected override event OnDisappearing() will occur.

  • asierdoasierdo Member ✭✭

    Thank you mates !!
    It works like Colex sais.

    protected override void OnAppearing()
    {
    base.OnAppearing();
    adapter.DeviceConnectionLost += lostEvent;
    }

    protected override void OnDisappearing()
    {
    base.OnDisappearing();
    adapter.DeviceConnectionLost -= lostEvent;
    }

Sign In or Register to comment.