ReactiveUI 消息总线
我正在测试ReactiveUI,它看起来非常好。
然而,我对MessageBus有点困惑。
示例代码:
var bus = new MessageBus();
int result = -1;
bus.Listen<int>().Subscribe(x => result = x);
bus.SendMessage(42);
它在调用 Assert 语句时确实有效,但在标准 WPF 应用程序中,结果值永远不会更新。这可能是由于 Scheduler 的实现造成的,但我还不太清楚。
欢迎任何提示。
I'm testing ReactiveUI, it seems very nice.
However, I am a bit puzzled by the MessageBus.
Sample code :
var bus = new MessageBus();
int result = -1;
bus.Listen<int>().Subscribe(x => result = x);
bus.SendMessage(42);
It does work when calling an Assert statement, but in a standard WPF application the result value is never updated. This is probably due to the Scheduler implementation, but it's not quite clear to me yet.
Any hint is welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
结果最终会更新(与调用
Dispatcher.BeginInvoke
相同),而不是立即更新。默认情况下,RxUI 在单元测试运行程序中以不同的方式安排事情,以便更轻松地编写单元测试 - 这就是您在单元测试运行程序输出中看到该警告的原因。如果您要执行以下操作:
您将看到消息框(如果没有,这肯定是一个错误!)。
为什么 MessageBus 会延迟?它使编写异步代码变得更加容易,因为您现在可以从其他线程发送消息,而不会因为访问错误线程上的对象而看到 WPF 可怕的 InvalidOperationException。
The result is eventually updated (the same as calling
Dispatcher.BeginInvoke
), not immediately. By default, RxUI schedules things differently in a unit test runner to make it easier to write unit tests - that's why you see that warning in the unit test runner output.If you were to instead do something like:
You will see the Message Box (if not, it's definitely a bug!).
Why is the MessageBus deferred? It makes it easier to write async code, since you can now SendMessage from other threads without seeing WPF's dreaded InvalidOperationException due to accessing objects on the wrong thread.