如何停止消息中心在 Xamarin.Forms 中多次停止订阅?

How to stop messaging center to stop subscribe multiple time in Xamarin.Forms?

我正在创建一个应用程序,它需要将参数发送到另一个页面并使用 Messagingcenter 发送参数,当我使用 MessagingCenter 发送时它会调用多次。

如果我使用的是 unscribe,那么下次就不会收到了。

MessagingCenter.Send(this, "Invoke", "Invokedtrue");

MessagingCenter.Subscribe<MyPage, string>(this, "Invoke", async (sender, arg) =>
{
    await Process(arg);
});
MessagingCenter.Unsubscribe<MyPage>(this,"Invoke");


**ListPage**

    private void ViewCell_Tapped(object sender, EventArgs e)
    {
        try
        {
            MessagingCenter.Send(this, "Invoke", "Invokedtrue");
        }
        catch (Exception ex)
        {
            Debug.Write(ex);
        }
    }

**Detail Page**

    MessagingCenter.Subscribe<ListPage, string>(this, "Invoke", async (sender, arg) =>
    {
        await Process(arg);
    });

    private async Task Process(string arg)
    {
        //Here is api call to view detail of particular record

        //Here I unsubscribe the MessagingCenter.
        MessagingCenter.Unsubscribe<ListPage>(this,"Invoke");
    }

我想使用订阅只发送一次并且只发送一次。

任何人都可以调查一下并建议我应该怎么做吗?

您是否只想发送和接收消息一次?然后您可以在收到消息后使用 Unsubscribe 方法。例如,您可以这样做:

 MessagingCenter.Subscribe<MyPage, string>(this, "Invoke", async (sender, 
   arg) =>
{
await Process(arg); 
MessagingCenter.Unsubscribe<MyPage>(this,"Invoke");
});

已更新

DetailPage上,可以在方法OnAppearing()中调用MessagingCenter.Subscribe,在方法OnDisappearing中调用MessagingCenter.Unsubscribe,如下:

protected override void OnAppearing()
    {
        base.OnAppearing();
       MessagingCenter.Subscribe<ListPage, string>(this, "Invoke", async (sender, arg) =>
        {
            Debug.Write("123456---->  get one msg");
            DisplayAlert("Alert", "We have received a message.", "OK");
        });
    }

    protected async override void OnDisappearing()
    {
        base.OnDisappearing();
        MessagingCenter.Unsubscribe<ListPage,string>(this, "Invoke");
    }
}

ListPage

async void OnTap (object sender, EventArgs e)  
    {
        await Navigation.PushAsync(new DetailPage());
        try
        {

            MessagingCenter.Send(this, "Invoke", "Invokedtrue");

            Debug.Write("123456---->  send one msg");

        }
        catch (Exception ex)
        {
            Debug.Write(ex);
        }

    }

注意:进入ListPage后,可以试试下面的代码:

  MainPage = new  NavigationPage( new ListPage());

IOS中的效果是:

完整demo的link是here,大家可以查看