I am creating an application and in that it need to send argument to the other page and send argument using the Messagingcenter when I send using MessagingCenter it call more than one time.
If I am using unscribe than in next time it is not receive next time.
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");
}
I want to send only one time using subscribe and send only one time.
Can anyone look into this and suggest me what should I have to do in that?
Do you want to send and receive message only one time? Then you can use Unsubscribe method after you receive the message. For example, you can do like this:
MessagingCenter.Subscribe<MyPage, string>(this, "Invoke", async (sender,
arg) =>
{
await Process(arg);
MessagingCenter.Unsubscribe<MyPage>(this,"Invoke");
});
Updated:
On DetailPage
, you can call MessagingCenter.Subscribe
in method OnAppearing()
and call MessagingCenter.Unsubscribe
in method OnDisappearing
, just as follows:
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");
}
}
On 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);
}
}
Note: when you enter into ListPage
, you can try the following code:
MainPage = new NavigationPage( new ListPage());
The link of full demo is here, you can check it.