Observable 在 SelectMany 之后仍然订阅

Observable still subscribed after SelectMany

我为 WPF 应用程序设置了标准 reactive-ui 路由,并且我有一个 ViewModel 可以实现的接口来提供标题信息。

public interface IHaveTitle
{
    IObservable<string> Title { get; }
}

在一个视图模型中,我正在执行以下操作(出于演示目的):

public IObservable<string> Title => Observable.Interval(TimeSpan.FromSeconds(5)).Select(_ => DateTime.Now.ToLongTimeString());

在我的 window 主屏幕中,我正在执行以下操作:

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 的使用。你说的是 "every time the CurrentViewModel changes, subscribe to this other observable"。由于这些 observables 永远不会完成,因此它们将永远 "active"。

您想要切换到新的可观察对象:

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