【问题标题】:Make a sealed class the Observer of its own Observable<T> property使密封类成为其自己的 Observable<T> 属性的观察者
【发布时间】:2020-08-19 14:00:00
【问题描述】:

我有一个密封的课程。它有一个属性 '

private IObservable<AnotherClass> observable

'。

  1. 我想让这个类作为观察者,监控上面属性的变化。
  2. 我想在此属性发生变化时调用 onNext()。
  3. 我想在 .onNext() 中调用自定义方法 1()。像 onNext(调用 Method1(传递可观察数据))。 由于这是一个密封类,我不能像在许多示例中发现的那样使用 Virtual onNext()。

我如何实现这些?

【问题讨论】:

    标签: c# observable system.reactive observer-pattern


    【解决方案1】:

    实现IObserver&lt;AnotherClass&gt;并订阅observable?

    public sealed class AnObserver : IObserver<AnotherClass>
    {
        private readonly IObservable<AnotherClass> observable;
    
        public AnObserver()
        {
            observable = ...;
            observable.Subscribe(this);
        }
    
        void IObserver<AnotherClass>.OnCompleted() { }
    
        void IObserver<AnotherClass>.OnError(Exception error) { }
    
        void IObserver<AnotherClass>.OnNext(AnotherClass value)
        {
            Method1(value);
        }
    
        public void Method1(AnotherClass value)
        {
           ...
        }
    }
    

    【讨论】:

    • 请避免实施IObserver&lt;AnotherClass&gt; - 它通常会出错。通过这样做,在这种情况下,您已经将类的内部工作方式暴露给了外部世界。
    • 当您调用Subscribe 时,您的代码中还有一个悬空的IDisposable。这应该会强制类实现IDisposable 进行清理。
    【解决方案2】:

    以下是我将如何处理这种情况。

    public sealed class ThisClass : IDisposable
    {
        private readonly IObservable<AnotherClass> observable;
        private readonly IDisposable subscription;
    
        public ThisClass()
        {
            observable = ...;
            subscription = observable.Subscribe(x => Method1(x));
        }
    
        private void Method1(AnotherClass value)
        {
           ...
        }
    
        private bool disposedValue = false;
    
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    subscription.Dispose();
                }
                disposedValue = true;
            }
        }
    
        public void Dispose()
        {
            Dispose(true);
        }
    }
    

    这不会向外界暴露任何不必要的东西,并且会在 dispose 时进行清理。

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多