WhenActivated是一种跟踪可释放对象的方式。除此之外,还可用于延迟ViewModel的设置,直到真正需要为止。WhenActivated还可以启动或停止对“热”可观察对象的响应,例如定期对网络终端执行ping操作或实时更新用户当前位置的后台任务。而且,当ViewModel加载时,可以使用WhenActivated触发启动逻辑。看一个示例:
public class ActivatableViewModel : IActivatableViewModel
{
public ViewModelActivator Activator { get; }
public ActivatableViewModel()
{
Activator = new ViewModelActivator();
this.WhenActivated(disposables =>
{
// Use WhenActivated to execute logic
// when the view model gets activated.
this.HandleActivation();
// Or use WhenActivated to execute logic
// when the view model gets deactivated.
Disposable
.Create(() => this.HandleDeactivation())
.DisposeWith(disposables);
// Here we create a hot observable and
// subscribe to its notifications. The
// subscription should be disposed when we'd
// like to deactivate the ViewModel instance.
var interval = TimeSpan.FromMinutes(5);
Observable
.Timer(interval, interval)
.Subscribe(x => { /* do smth every 5m */ })
.DisposeWith(disposables);
// We also can observe changes of a
// property belonging to another ViewModel,
// so we need to unsubscribe from that
// changes to ensure we won't have the
// potential for a memory leak.
this.WhenAnyValue(...)
.InvokeCommand(...)
.DisposeWith(disposables);
});
}
private void HandleActivation() { }
private void HandleDeactivation() { }
}
如何确保ViewModel被激活?
如果ViewModel实现IVewFor
接口,则框架将确保从ViewModel到View的链接。记住要使ViewModel作为DependencyProperty
,并且在IVewFor<TVeiwModel>
的构造函数中添加对WhenActivated
的调用。
视图
每当将一个对象订阅到另一个对象公开的事件时,都会引起内存泄漏。对于基于XAML的平台,尤其是可能不会自动回收依赖属性引用的对象/事件。 ··· 阅读全文