【发布时间】:2023-03-16 20:13:01
【问题描述】:
我想同步对BehaviorSubject<T> 的访问,所以我希望使用Subject.Synchronize。但是,我对这个界面有几个痛点,我想知道我是否错过了一种更令人满意的做事方式。
首先,我不得不同时存储原始主题和同步主题。这是因为我有时会在BehaviorSubject<T> 上使用Value 属性。也是因为Synchronize的返回值不是一次性的,所以我必须存储原始主题的一个实例才能正确处理。
其次,Synchronize的返回值为ISubject<TSource, TResult>,与ISubject<T>不兼容。
所以我最终得到了这样的代码:
public class SomeClass
{
private readonly BehaviorSubject<string> something;
private readonly ISubject<string, string> synchronizedSomething;
public SomeClass()
{
this.something = new BehaviorSubject<string>(null);
// having to provide the string type here twice is annoying
this.synchronizedSomething = Subject.Synchronize<string, string>(this.something);
}
// must remember to use synchronizedSomething here (I forgot and had to edit my question again, showing how easy it is to screw this up)
public IObservable<string> Something => this.synchronizedSomething.AsObservable();
// could be called from any thread
public void SomeMethod()
{
// do some work
// also must be careful to use synchronizedSomething here
this.synchronizedSomething.OnNext("some calculated value");
}
public void Dispose()
{
// synchronizedSomething is not disposable, so we must dispose the original subject
this.something.Dispose();
}
}
我是否缺少更清洁/更好的方法?为了清楚起见,我希望能够做的是这样的事情(伪代码):
public class SomeClass
{
private readonly IBehaviorSubject<string> something;
public SomeClass()
{
this.something = new BehaviorSubject<string>(null).Synchronized();
}
public IObservable<string> Something => this.something.AsObservable();
// could be called from any thread
public void SomeMethod()
{
// do some work
this.something.OnNext("some calculated value");
}
public void Dispose()
{
this.something.Dispose();
}
}
【问题讨论】:
-
当你说同步访问时,你的意思是你想要原子写入吗?还是您的意思是您想要序列化读取(订阅者)?您能否将示例扩展为 1) 编译 - 您在 ctor 中缺少
BehaviorSubject的默认值,2) 公开如何使用SomeClass- 您只有一个 ctor 和一个Dispose方法并且从不公开主题。 -
@LeeCampbell:已编辑
标签: c# .net system.reactive