我有一个公开IObservable的类。这是这样的:
private readonly Subject<(int moduleNumber, int channelNumber, object oldValue, object newValue)> _channelChanged =
new Subject<(int moduleNumber, int channelNumber, object oldValue, object newValue)>();
/// <summary>
/// Subscribe to this if you want to be notified as soon as a channel changed its value.
/// </summary>
public IObservable<(int moduleNumber, int channelNumber, object oldValue, object newValue)> ChannelChanged => _channelChanged.AsObservable();
我创建了此类的一个实例,尝试像这样订阅此IObservable:
public void TestDataModelEventWhenAnalogueChannelChanged()
{
var instance = new MyClassThatContainsTheIObservable();
IDisposable subscription = instance.ChannelChanged.Subscribe(OnChannelChanged);
// do stuff that leads to a channel changing its value
}
private void OnChannelChanged((int moduleNumber, int channelNumber, object oldValue, object newValue) e)
{
// Assert the correct arguments appear here
}
编译器说他不能从方法组转换为IObserver。我明白了– intellisense告诉我,我需要为Subscribe()提供一个IObserver。但是后来我找到了本教程:
https://rehansaeed.com/reactive-extensions-part1-replacing-events/
如果您查看他的订阅示例,您会发现他也提供了一种方法。 查看以下问题的答案,似乎也可以使用lambda表达式进行订阅:
Reactive Observable Subscription Disposal
尝试此操作时,我的编译器告诉我相同的内容:他无法将Lambda表达式转换为IObserver。
我在做什么错?我真的必须创建一个实现IObserver的整个类吗?
答案 0 :(得分:-1)
我猜你错过了using System;
。在Subscribe
命名空间中定义了接受动作的System
扩展名,因为IObservable
本身是在该命名空间中定义的。