Xamarin.表单呼叫信息中心的次数每次都在增加



我有一个问题,我发送一次消息,Subscriber被调用一次,但下次它被调用两次,以此类推…这是我的代码。这是消息发送者

public void OnSuccess(Java.Lang.Object result)
{
UploadTask.TaskSnapshot taskSnapShot = (UploadTask.TaskSnapshot)result;
string downloadURL = taskSnapShot.DownloadUrl.ToString();
string fileName = taskSnapShot.Metadata.Name;
GBPaperReceipt.Model.ImageFile imageFile = new Model.ImageFile
{
FileName = fileName,
FilePath = downloadURL
};
MessagingCenter.Send((App)Xamarin.Forms.Application.Current, MessageStrings.ImageUploadEvent, imageFile);
//save this live storage image url in receipt table
//MessagingCenter.Send<Xamarin.Forms.Application, string>((Xamarin.Forms.Application)Xamarin.Forms.Application.Current, ChatModuleConstant.UploadMediaEvent, downloadURL);
}

这是消息接收器

MessagingCenter.Subscribe<App, ImageFile>((App)Application.Current, MessageStrings.ImageUploadEvent,async (a, imageFile) =>
{
_viewModel.Receipt.ImagePath = imageFile.FilePath;
_viewModel.Receipt.ImageName = imageFile.FileName;
try
{
await DependencyService.Get<IReceiptService>().SaveReceipt(_viewModel.Receipt);
}
catch (Exception ex)
{
await DisplayAlert(
"Error!", ex.Message, "OK");
}

DependencyService.Get<ICamera>().DeletePhoto(_viewModel._imageToBeDeletedOnSaveCommand);
Dialogs.HideLoading();
Application.Current.MainPage = new NavigationPage(new DashboardPage());
});

取消订阅

protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<App, string>((App)Application.Current, MessageStrings.ErrorEvent);
MessagingCenter.Unsubscribe<App, string>((App)Application.Current, MessageStrings.ImageUploadEvent);
}

特别是在导航页面中使用页面时,每当页面进入视图时,都会添加订阅事件。如果您来回导航几次,您对messagingcenter的订阅将被添加几次,导致您的事件加倍。

最安全的方法是在页面构造函数中订阅,即使在这种情况下,也可能需要先取消订阅,然后再订阅。

你的出现/消失方法可能也有效,但我不完全确定出现/消失的方法是否能保证你开火。

不过,你也可以试着把你的退订单移到基地前面。OnDisappearing((,因为您应该在调用基类对页面进行内部拆解之前取消订阅。

如果不起作用,请订阅构造函数。

最新更新