gpt4 book ai didi

c# - ReactiveUI命令退订

转载 作者:行者123 更新时间:2023-12-03 10:20:35 25 4
gpt4 key购买 nike

我有2个 View 和2个ViewModel:

第一 View :

public partial class FirstView : Page
{
FirstViewModel ViewModel;
public FirstView()
{
ViewModel = new FirstViewModel();
ViewModel.ShowSecondView.Subscribe(_ =>
{
NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
});

this.DataContext = ViewModel;
InitializeComponent();
}
}

第一个ViewModel:
public class FirstViewModel
{
SecondViewModel ChildViewModel;
public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
public FirstViewModel()
{
ChildViewModel = new SecondViewModel();
ShowSecondView = ReactiveCommand.Create(() =>
{
ChildViewModel.Reconfigure(...);
});
}
}

第二种观点:
public partial class SecondView : Page
{
SecondViewModel ViewModel;
public SecondView(SecondViewModel viewModel)
{
ViewModel = viewModel;
ViewModel.GoBack.Subscribe(_ =>
{
DoSomethingHard();
if(NavigationService != null) NavigationService.GoBack();
});
this.DataContext = ViewModel;
InitializeComponent();
}
}

第二个ViewModel:
public class SecondViewModel
{
public ReactiveCommand<Unit, Unit> GoBack { get; set; }
public FirstViewModel()
{
VeryLongInitialization();
GoBack = ReactiveCommand.Create(() => { });
}
public void Reconfigure(...)
{ ... }
}

因此,当我多次运行 FirstViewModel.ShowSecondView和多次运行 SecondViewModel.GoBack时, DoSomethingHard()在每个创建的SecondView上也执行了多次。

为什么我要一次在 ChildViewModel中创建 FilstViewModel?因为创建 SecondViewModel需要很长时间。而且我不会每次都重新创建 SecondViewModel,而只是重新配置它。

我的问题是如何取消订阅 ViewModel.GoBack.Subscribe中的 SecondView

附言也许我不应该在 SecondView中重新创建 FirstView,而要像 SecondViewModel一样重新配置它?

更新1 (感谢Julien Mialon)

我添加 IDisposable goBackSubscr,它可以工作!我执行它正确吗?
public partial class SecondView : Page
{
SecondViewModel ViewModel;
IDisposable goBackSubscr;
public SecondView(SecondViewModel viewModel)
{
ViewModel = viewModel;
goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
{
DoSomethingHard();
if(NavigationService != null) NavigationService.GoBack();
goBackSubscr.Dispose();
});
this.DataContext = ViewModel;
InitializeComponent();
}
}

最佳答案

在您的 View 上使用WhenAcitvated:
在页面的构造函数中(必须为IViewFor):

 this.WhenActivated(
disposables =>
{
ViewModel.Command.Subscribe(...).(disposables);
});

关于c# - ReactiveUI命令退订,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47674284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com