0

我有一个问题,我发送一次消息并调用一次订阅者,但下一次调用它两次等等......这是我的代码。这是消息发送者

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);
    }
4

1 回答 1

0

尤其是在导航页面中使用您的页面时,只要页面出现,您的订阅事件就会被添加。如果您来回导航几次,您对消息中心的订阅将被添加多次,从而导致您的事件双重触发。

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

您的 Appearing/Disappearing 方法也可能有效,但是我不完全确定 Appearing/Disappearing 方法是否可以保证您被解雇。

但是,您也可以尝试将取消订阅移动到 base.OnDisappearing() 之前,因为您应该在调用基类对页面进行内部拆卸之前取消订阅。

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

于 2018-07-18T07:49:45.643 回答