简体   繁体   English

WinForms中的RX和Model-View-Presenter

[英]RX and Model-View-Presenter in WinForms

I am new to RX and I'm trying to adapt it to my WinForms application. 我是RX的新手,我正在尝试使其适应我的WinForms应用程序。 (Un?)fortunately I use MVP pattern where the View is abstracted from any specific implementation (eg WinForms). (Un?)幸运的是,我使用MVP模式,其中View是从任何特定实现(例如WinForms)中抽象出来的。

When RX-friendly Model produces new value, presenter gets it and tries to update the view. 当RX友好模型产生新值时,演示者获取它并尝试更新视图。 The problem is that I cannot observe on the main thread since I have no reference to WinForms Control. 问题是,由于我没有引用WinForms控件,因此无法在主线程上进行观察。

I found a few solutions but neither of them looks well to me: 我找到了一些解决方案,但对我来说都不满意:

  1. Create a Control property in the view so that I could observe on it. 在视图中创建一个Control属性,以便可以对其进行观察。
  2. Use Control.Invoke inside property setters which are modified by the Presenter 使用由演示者修改的内部属性设置器中的Control.Invoke
  3. Create an extension method similar to: 创建类似于以下内容的扩展方法:

:

public static IObservable<T> ObserveOn<T>(this IObservable<T> observable, IMyView view)
{
    var control = (Control)view;
    return observable.ObserveOn(control);
}

Is there a nice way to handle this? 有没有解决这个问题的好方法?

EDIT: I found another solution which I like the most: 编辑:我发现了另一个我最喜欢的解决方案:

private readonly SynchronizationContext _syncContext;

public Presenter()
{
    _syncContext = SynchronizationContext.Current; //I can observe on this one with a reasonable assumption that presenter is created on the UI thread
}

Is the presenter running on the UI thread at the time that it subscribes to the model? 演示者在订阅模型时是否在UI线程上运行? Just use ObserveOnDispatcher at the time your present subscribes to the observable: 您现在订阅可观察对象时,只需使用ObserveOnDispatcher

// from your presenter code, which is running on the UI thread:
model.ObservableProperty.ObserveOnDispatcher().Subscribe(p => updateView(p));

Edit: 编辑:

Alternatively, you can get Rx-Windows Forms Helper and have your IMyView interface expose an IScheduler (which it creates by calling new ControlScheduler(control) ). 或者,您可以获取Rx-Windows Forms Helper并让您的IMyView界面公开一个IScheduler (它通过调用new ControlScheduler(control)创建)。

Then you can implement your ObserveOn(observable, view) extension method as: 然后,您可以将ObserveOn(observable, view)扩展方法实现为:

public static IObservable<T> ObserveOn<T>(this IObservable<T> observable, IMyView view)
{
    return observable.ObserveOn(view.Scheduler);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM