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

标签 c# xaml xamarin xamarin.forms messagingcenter

我正在创建一个应用程序,因为它需要将参数发送到另一个页面并使用 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 并调用 MessagingCenter.Unsubscribe在方法 OnDisappearing 中,如下所示:

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中的效果是: enter image description here

完整的demo链接是here,大家可以去看看。

关于c# - 如何停止消息中心在 Xamarin.Forms 中多次停止订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582502/

相关文章:

c# - REST API URL 模式

c# - 如何创建 xamarin 表单跨平台汉堡幻灯片 View

ios - 如何在 xamarin ios pcl 中使用 protobuf-net

c# - 相当于asp.net中的javadoc

c# - 带有签名证书的 WCF net.tcp

c# - 如何在 ASP.NET MVC 中使用 javascript 编写 Action 链接?

c# - 修改绑定(bind) DataGrid 的结果

c# - Silverlight 依赖属性未在自定义控件中通知

wpf - slider 不适用于触摸输入

c# - InstantiateViewController 调用 ViewDidLoad