注册后组合 IObservables 和清理

Composing IObservables and cleaning up after registrations

我在 class 中有一些代码接收 FileSystemWatcher 事件并将它们扁平化为我域中的事件:

(请注意,*AsObservable 方法是我项目中其他地方的扩展,他们按照他们说的去做。)

            watcher = new FileSystemWatcher(ConfigurationFilePath);

            ChangeObservable = Observable
                .Merge(
                    watcher.ChangedAsObservable().Select((args) =>
                    {
                        return new ConfigurationChangedArgs
                        {
                            Type = ConfigurationChangeType.Edited,
                        };
                    }),
                    watcher.DeletedAsObservable().Select((args) =>
                    {
                        return new ConfigurationChangedArgs
                        {
                            Type = ConfigurationChangeType.Deleted,
                        };
                    }),
                    watcher.RenamedAsObservable().Select((args) => 
                    {
                        return new ConfigurationChangedArgs
                        {
                            Type = ConfigurationChangeType.Renamed,
                        };
                    })
                );

            ChangeObservable.Subscribe((args) =>
            {
                Changed.Invoke(this, args);
            });

在我学习的过程中,我正在努力解决的问题是关于命名、所有权和清理由这样的代码返回的 IObservableIDisposable 的最佳实践。

那么,一些具体的问题:

其他提示和建议总是非常感谢!


Is it okay to leak IObservables from a class that creates them? For example, is the property I'm assigning this chain to okay to be public?

是的。

Does the property name ChangeObservable align with what most people would consider best practice when using the .net reactive extensions?

主观题。也许 FileChanges?从类型可以清楚地看出它是一个可观察的事实。

Do I need to call Dispose on any of my subscriptions to this chain, or is it safe enough to leave everything up to garbage collection when the containing class goes out of scope?

末尾的 ChangeObservable.Subscribe 可以永远存在,防止对象在订阅事件时被垃圾回收,尽管这也可能是您的意图。运营商订阅通常没问题。我看不到您的 ChangedAsObservable 类函数的代码。如果它们不包含 Subscribe 或事件订阅,它们可能也没有问题。

Keep in mind, I'm observing events from watcher, so there's some shared lifecycle there.

由于 FileWatcher 实现了 IDisposable,您可能应该围绕它使用 Observable.Using,这样您就可以组合生命周期。

Is it okay to take an observable and wire them into an event on my own class (Changed in the example above), or is the idea to stay out of the native .net event system and leak my IObservable?

我更愿意留在 Rx。事件订阅的问题在于它们通常永远存在。您失去了控制订阅生命周期的能力。他们也感觉更加原始。但同样,这有点主观。