[英]Observable still subscribed after SelectMany
我为WPF应用程序设置了标准反应式ui路由,并且具有ViewModel可以实现以提供标题信息的接口。
public interface IHaveTitle
{
IObservable<string> Title { get; }
}
在一个视图模型中,我正在执行以下操作(出于演示目的):
public IObservable<string> Title => Observable.Interval(TimeSpan.FromSeconds(5)).Select(_ => DateTime.Now.ToLongTimeString());
在主窗口屏幕中,我正在执行以下操作:
disposer(
ViewModel.Router.CurrentViewModel
.SelectMany(vm =>
((vm as IHaveTitle)?.Title.StartWith("") ??
Observable.Return("")).Select(s => string.IsNullOrEmpty(s) ? vm.UrlPathSegment : $"{vm.UrlPathSegment} > {s}"))
.ObserveOn(RxApp.MainThreadScheduler)
.BindTo(this, w => w.Title));
其中disposer
是传递到this.WhenActivated
扩展方法中的Action<IDisposable>
。
现在,当我四处导航时,标题确实会更改以反映UrlPathSegment
,而在主视图模型上,标题会更新以每5秒显示一次时间。
但是,我看到的问题是,即使导航到其他视图模型,在主视图模型上可观察到的标题仍会导致标题发生更改。
我的问题确实是:如何预防这种情况? 鉴于我基于CurrentViewModel
选择,当我离开时为什么它不分离?
问题是使用SelectMany
。 您说的是“每当CurrentViewModel
更改时,都订阅另一个可观察的对象”。 由于这些可观测对象永远不会完成,因此它们将永远保持“活动”状态。
相反,您想切换到新的可观察对象:
disposer(
ViewModel.Router.CurrentViewModel
.Select(vm =>
((vm as IHaveTitle)?.Title.StartWith("") ??
Observable.Return("")).Select(s => string.IsNullOrEmpty(s) ? vm.UrlPathSegment : $"{vm.UrlPathSegment} > {s}"))
.Switch()
.ObserveOn(RxApp.MainThreadScheduler)
.BindTo(this, w => w.Title));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.