在 .NET Standard 库中访问 Dispatcher IScheduler

Accessing Dispatcher IScheduler in .NET Standard libraries

This question 描述了如何通过将 UI 调度程序传递给 Throttle 来确保 IObservable<>.Throttle 在 UI 线程上运行。但是,我的 Observables 是在基于 .NET Standard 1.5 的共享库中定义的。 .NET Standard 中是否有 DispatcherScheduler.Instance 的等价物,或者我应该从消费 (WPF/UWP/etc) 库中注入调度程序?

.NET Standard 的 System.Reactive 程序集中不存在 class DispatcherScheduler。

一种可能的解决方法是将 SynchronizationContextScheduler 与当前的 SynchronizationContext 一起使用。当您在 UI 线程上调用 ObserveOn() 时,可观察对象的处理程序将在 UI 线程上 运行。

ObserveOn() 未在 UI 线程上调用时,整个过程不起作用。为避免这种情况,您可以创建类似 AppContext 对象的东西,在 UI 初始化发生时对其进行设置,并使其在您的应用程序中可分发。将 SynchronizationContext.Current 保存在此 AppContext 中,您可以在任何具有 AppContext.

的地方创建 UI 线程上的观察者
IObservable<EventArgs> myObservable = GetSomeObservableEvents();
var myScheduler = new SynchronizationContextScheduler(SynchronizationContext.Current);
myObservable.ObserveOn(myScheduler).Subscribe(ev =>
{
    // some code that should run on UI thread
});

我在 Xamarin.Forms 2.5.0 项目中这样使用它,我在 .NET Standard 2.0 中有一个包含 ViewModels、Views 等的应用程序项目。

此答案(至少)在以下条件下有效:

  • .NET Standard 项目版本为 2.0
  • System.Reactive 有版本 4.0.0-preview00001