如何在ReactiveUI 6.0中正确地制作UI线程

时间:2015-01-01 01:20:45

标签: reactiveui

我有一个像这样的Observable:

var posChangeObs =
            Observable.Publish<DisplayPositionModel>(
                Observable
                    .FromEventPattern<EventHandler<PositionEventArgs>, PositionEventArgs>(h => cine.PositionChange += h,
                                                                                          h => cine.PositionChange -= h,
                                                                                          RxApp.MainThreadScheduler)
                    .Select(x => new DisplayPositionModel(cine.ToDisplayPosition(x.EventArgs.Position), x.EventArgs.LinearFrameIndex)),
                    new DisplayPositionModel(cine.ToDisplayPosition(cine.CurrentCinePosition), cine.CurrentLinearCinePosition));

此跟踪的事件将始终发生在其他线程上。我把这个Observable传递给了很多不同的视图模型。在某些视图模型中,eventArgs使用ToProperty设置为属性。在其他人我只是订阅和DoStuff(TM)。

我想知道的是如何确保这些内容始终被封送到UI线程。我尝试在所有ToProperty和Subscribe调用上添加ObserveOn(RxApp.Main ...),但这不起作用。

以下是我现在如何使用ToProperty并获得跨线程异常的示例:

posChangeObs.ToProperty(this, x => x.CurrentPosition, out _CurrentPosition);

以下是订阅的示例:

posChangeObs
            .Select(x => x.LinearFrameIndex)
            .Subscribe(x => this.CurrentLinearFrameIndex = x,
            e =>
            {
                throw e;
            });

1 个答案:

答案 0 :(得分:2)

答案是将ObserveOn(RxApp.MainThreadScheduler)添加到FromEventPattern的返回中。像这样 var posChangeObs = Observable.Publish<Position>( Observable.FromEventPattern<EventHandler<PositionEventArgs>,PositionEventArgs>(h => x.PositionChange += h, h => x.PositionChange -= h) .ObserveOn(RxApp.MainThreadScheduler) .Select(x => ...));