是否可以通过一种方法订阅IObservable ?

问题描述 投票:0回答:1

我有一个公开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的整个类吗?

c# system.reactive reactive
1个回答
-1
投票

我想你已经错过了using System;。在Subscribe命名空间中定义了接受动作的System扩展名,因为IObservable本身是在该命名空间中定义的。

© www.soinside.com 2019 - 2024. All rights reserved.